JavaScript登录验证2.0
程序员文章站
2022-04-10 09:07:54
要求账号:3-15位并且不能数字开头密码:6-18位并且不能全是数字或者全是字符演示演示地址采用正则表达式进行字符串的判断优化了部分代码账号判断var userNameCheck = /(\D+\d+)|(\D+\D+)/;密码判断var pwdReg = /(\D+\d+)|(\d+\D+)/;页面代码账号:
要求
账号:3-15位并且不能数字开头
密码:6-18位并且不能全是数字或者全是字符
演示
采用正则表达式进行字符串的判断
优化了部分代码
账号判断
var userNameCheck = /(\D+\d+)|(\D+\D+)/;
密码判断
var pwdReg = /(\D+\d+)|(\d+\D+)/;
页面代码
账号:<input type="text" id="userName" name="userName" placeholder="3-15位并且不能以数字开头" onblur="checkUserName()"/>
<span id="userNameShow"></span><br>
密码:<input type="text" id="pwd" name="pwd" placeholder="6-18位,包含字母和数字" onblur="checkPwd()"/>
<span id="pwdShow"></span><br>
<input type="button" onclick="login()" value="登录"/><br/>
<span id="resultShow"></span>
完整的JavaScript代码
<script>
function checkUserName() {
var userName = document.getElementById("userName").value;
var userNameShowDom = document.getElementById("userNameShow");
if (userName.length >= 3 && userName.length <= 15) {
var userNameCheck = /(\D+\d+)|(\D+\D+)/;
if (userNameCheck.test(userName)) {
userNameShowDom.innerText = "验证通过";
userNameShowDom.style.color = "green";
return true;
} else {
userNameShowDom.innerText = "不能以数字开头";
userNameShowDom.style.color = "red";
return false;
}
} else {
userNameShowDom.innerText = "长度不符合要求";
userNameShowDom.style.color = "red";
return false;
}
}
function checkPwd() {
var pwd = document.getElementById("pwd").value;
var pwdShowDom = document.getElementById("pwdShow");
if (pwd.length >= 6 && pwd.length <= 18) {
var pwdReg = /(\D+\d+)|(\d+\D+)/;
if (pwdReg.test(pwd)) {
pwdShowDom.innerText = "验证通过"
pwdShowDom.style.color = "green";
return true;
} else {
pwdShowDom.innerText = "必须同时含有数字和字符"
pwdShowDom.style.color = "red";
return false;
}
} else {
pwdShowDom.innerText = "长度不符合要求"
pwdShowDom.style.color = "red";
return false;
}
}
function login() {
if (checkUserName() && checkPwd())
alert("登陆成功!")
}
</script>
本文地址:https://blog.csdn.net/m0_49926319/article/details/109256255