這篇文章主要為大家詳細(xì)介紹了javascript html5實(shí)現(xiàn)表單驗(yàn)證的具體代碼,感興趣的小伙伴們可以參考一下
表單驗(yàn)證為終端用戶檢測(cè)無效的數(shù)據(jù)并標(biāo)記這些錯(cuò)誤,是一種用戶體驗(yàn)的優(yōu)化。
下面展現(xiàn)瀏覽器自帶的驗(yàn)證功能也可在移動(dòng)端中查看:
HTML部分:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
<title>html5 表單驗(yàn)證</title>
</head>
<body>
<form action="#" id="formValid" class="myform" novalidate="novalidate" onsubmit="return checkForm()">
<fieldset>
<div class="form-group">
<label for="name">名稱</label>
<div>
<input type="text" class="form-control" id="name" name="name" required/>
<span class="form-error">不能為空</span>
</div>
</div>
<div class="form-group">
<label for="email">郵箱</label>
<div>
<input type="email" class="form-control" id="email" name="email" required/>
<span class="form-error">郵箱格式不正確</span>
</div>
</div>
<div class="form-group">
<label>省份</label>
<select name="province" class="form-control">
<option value="">請(qǐng)選擇</option>
<option value="s">四川</option>
<option value="c">重慶</option>
</select>
</div>
<input type="submit" class="btn" value="提交"/>
</fieldset>
</form>
</body>
</html>
CSS部分:
fieldset{border: 0;}
.myform .form-control{
display: block;
padding: 5px;
width: 100%
}
.myform input:focus:invalid + .form-error{
display: inline;
}
.myform .form-error{
display: none;
position: absolute;
margin-top: .7em;
padding: 1px 2px;
color: #fff;
font-size: .875rem;
background: #f40;
}
.myform .form-error:after{
position: absolute;
content: "";
top: -.5em;
left: .5em;
z-index: 100;
display: inline-block;
width: 0;
height: 0;
vertical-align: middle;
border-bottom: .5em solid #f40;
border-right: .5em solid transparent;
border-left: .5em solid transparent;
border-top: 0 dotted;
transform: rotate(360deg);
overflow: hidden;
}
.btn{
padding: 5px 20px;
}
JavaScript部分:
function checkForm(){
var myform = document.getElementById("formValid");
return check(myform.elements);
}
function check(eles){
var ele;
for(var i = 0;i<eles.length;i++){
ele = eles[i];
if(ele.nodeName == "SELECT"){
if(!ele.selectedIndex){
alert("請(qǐng)選擇省份");
return false;
}
}else if(ele.name){
if(!ele.checkValidity()){
ele.focus();
return false;
}
}
}
return true;
}
以上就是javascript結(jié)合html5實(shí)現(xiàn)表單驗(yàn)證的全部代碼,希望對(duì)大家的學(xué)習(xí)有所幫助。