html5标准推荐的表单写法
HTML页面:
<div class="container">
<!--html5标准推荐的表单写法-->
<form action="">
<div class="form-group">
<label for="uname" class="control-label">用户名:</label>
<input type="text" class="form-control" id="uname" required minlength="3" maxlength="6" autocomplete="off" autofocus>
<span class="help-block primary" >用户名可以包含数字和字母</span>
</div>
<div class="form-group">
<label for="upwd" class="control-label">密码:</label>
<input type="password" class="form-control" id="upwd">
<span class="help-block primary" >密码长度在6-12位之间</span>
</div>
<div class="form-group">
<label for="umail" class="control-label">邮箱:</label>
<input type="email" class="form-control" id="umail">
<span class="help-block primary" >请注意邮箱格式</span>
</div>
<div class="form-group">
<label for="umail" class="control-label"></label>
<input type="submit" class="form-control success">
</div>
</form>
</div>
<script>
// 对用户名进行输入验证
uname.onblur=function () {
if(this.validity.valueMissing){
var msg="用户名不能为空";
this.nextElementSibling.innerHTML=msg;
this.nextElementSibling.className="help-block danger";
this.setCustomValidity(msg);
}else if(this.validity.tooShort){
var msg="用户名不能短于三位";
this.nextElementSibling.innerHTML=msg;
this.nextElementSibling.className="help-block danger";
this.setCustomValidity(msg);
}else if(this.validity.tooLong){
var msg="用户名不能超过6位";
this.nextElementSibling.innerHTML=msg;
this.nextElementSibling.className="help-block danger";
this.setCustomValidity(msg);
}else{
var msg="用户名验证正确";
this.nextElementSibling.innerHTML=msg;
this.nextElementSibling.className="help-block success";
this.setCustomValidity("");
}
}
css页面:
*{
box-sizing:border-box;
}
.container{
width:500px;
min-height: 400px;
margin:100px auto 0 auto;
padding:1.5em;
border:1px solid #aaa;
border-radius: 4px;
}
.form-group:not(:last-child){
margin-bottom: 15px;
}
.control-label{
display:inline-block;
width: 70px;
text-align: right;
vertical-align: middle;
}
.form-control{
padding: 4px;
border:1px solid #aaa;
width:200px;
vertical-align: middle;
}
.help-block{
font-size: 0.8em;
padding: 4px;
border: 1px solid transparent;
border-radius:2px;
color: #ffffff;
}
.primary{
background:#ccc;
border-color:#aaa;
}
.danger{
background:#d22;
border-color:#a00;
}
.success{
background:#2d2;
border-color:#0a0;
}
完成后的页面:
需要其他表单元素及js验证可自行添加.