JavaScript正则表达案例之表单检
要求
账户名不能以数字开头,长度在6~18之间,不能有非字母,数字的符号出现
密码长度要大于6,弱表示只有小写字母,或者大写字母或者数字
中表示只有数字、小写字母、大写字母
强表示包含数字、小写字母、大写字母
效果
完整源码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>表单验证</title>
<style>
*{
margin: 0px;
padding: 0px;
text-decoration: none;
}
body{
display: flex;
align-items: center;
justify-content: center;
margin-top: 100px;
}
#d1{
display: block;
text-align: center;
width: 200px;
height: 300px;
background-color: rgba(224, 67, 190, 0.24);
border-radius: 14px;
}
#d2{
width: inherit;
margin-top: 50px;
height: auto;
text-align: center;
}
input{
border: none;
height: 30px;
margin-top: 15px;
background-color: rgba(207, 105, 255, 0);
border-bottom: solid rgba(252, 235, 248, 0.89);
outline: none;
}
p{
font-size: 6px;
color: #999695;
}
</style>
</head>
<body>
<div id="d1">
<div id="d2">
<input type="text" placeholder="账号">
<p id="message">6~18个字符,可以使用字母数字下划线,必须以字母开头</p>
<input type="text" placeholder="密码">
<p id="password"></p>
</div>
</div>
<script>
var d2 = document.getElementById("d2");
var mes = document.getElementById("message");
var pas = document.getElementById("password");
var inputs = d2.getElementsByTagName("input");
inputs[0].onblur = function () {
var username = this.value;
if(username.length<6){//判断用户名长度小于6
mes.innerText = "!长度小于6";
mes.style.color = "red";
}else {
if(username.length>18){//判断用户名长度小于6
mes.innerText = "!长度大于18";
mes.style.color = "red"
}else {
if(!/^[a-zA-Z]/.test(username)){
mes.innerText = "!不是字母开头";
mes.style.color = "red"
}else{
if(/\W/.test(username)){
mes.innerText = "!包含非字母下划线数字的符号";
mes.style.color = "red"
}else {
mes.innerText = "✔符合要求";
mes.style.color = "green";
}
}
}
}
}
inputs[1].onkeyup = function () {
pas.style.display = "none";
var password = this.value;
if(password.length>6) {
if (/^\d+$/.test(password) || /^[a-z]+$/.test(password) || /^[A-Z]+$/.test(password)) {
pas.style.display = "block";
pas.innerText = "密码强度:弱";
pas.style.color = "red";
} else {
if (/\d/.test(password) && /[a-z]/.test(password) && /[A-Z]/.test(password) && /\W/.test(password)) {
pas.style.display = "block";
pas.innerText = "密码强度:强";
pas.style.color = "red";
} else {
pas.style.display = "block";
pas.innerText = "密码强度:中";
pas.style.color = "red";
}
}
}
}
</script>
</body>
</html>