经典表单验证

html部分:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<link rel="stylesheet" href="1.css" />
</head>
<body>
<div class="container">
<form action="1.php">
<div class="form-group">
<label for="uname" class="control-label">用户名:</label>
<input type="text" id="uname" name="uname" class="form-control" required minlength="3" autofocus autocomplete />
<span class="help-block">用户名可以是数字或者字母</span>
</div>
<div class="form-group">
<label for="name" class="control-label">用户:</label>
<input type="text" id="name" name="uname" class="form-control" required minlength="3" autofocus autocomplete />
<span class="help-block">用户名可以是数字或者字母</span>
</div>
<div class="form-group">
<label for="" class="control-label"></label>
<input type="submit" value="请提交注册信息" class="form-control" />
</div>
</form>
</div>
<script type="text/javascript" src="1.js"></script>
</body>
</html>

css部分;

*{box-sizing:border-box}
body{margin:0}
.container{
600px;
min-height:300px;
padding:20px;
margin:100px auto;
border:1px solid #aaa;
border-radius:4px;
box-shadow:0 0 6px #aaa;
}
.form-group{
margin-bottom:1em;
}
.control-label{
80px;
display:inline-block;
text-align:right;
}
.form-control{
padding:5px 6px;
border:1px solid #aaa;
border-radius:3px;
180px;
}
.help-block{
background:#aaa;
color:#fff;
padding:5px 6px;
border:1px solid #888;
border-radius:3px;
}
.help-block.danger{
background:#c00;
border:1px solid #a00;
}
.help-block.success{
background:#0c0;
border:1px solid #0a0;
}

js部分;

uname.onblur=function(){
if(this.validity.valueMissing){
var msg="用户名不能为空";
this.nextElementSibling.innerHTML=msg;
this.nextElementSibling.className="help-block danger";
this.setCustomValidity(msg);
}else{
this.nextElementSibling.innerHTML="用户名格式合法";
this.nextElementSibling.className="help-block success";
this.setCustomValidity('');
}
}

原文地址:https://www.cnblogs.com/liuhuilh/p/6692228.html