效果展示:
表单验证.png<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.main{
width: 500px;
margin: 0 auto;
}
ul li{
list-style: none;
border:1px solid #000;
color: red;
}
</style>
</head>
<body>
<div class="main">
<form method="post" action="http://www.baidu.com">
<ul>
<li>
用户名:
<input type="text" required placeholder="不能超过10位" maxlength="10">
<em></em>
</li>
<li>
密码:
<input type="password" required placeholder="长度不超过6位" maxlength="6">
<em></em>
</li>
<li>
邮箱:
<input type="email" required placeholder='请输入邮箱地址'>
<em></em>
</li>
<li>
手机:
<input type="tel" required placeholder='请输入手机号' pattern='(^0{0,1}\d{11}$)'>
<em></em>
</li>
<li>
身份证:
<input type="text" required pattern='^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$'>
<em></em>
</li>
<li>
<input id="sub" type="submit" value="注册">
</li>
</ul>
</form>
</div>
</body>
<script>
var form = document.getElementsByTagName("form")[0];
var inps = document.getElementsByTagName("input");
var ems = document.getElementsByTagName("em");
var sub = document.getElementById("sub");
function success(inputs){
if(inputs.checkValidity()){
return true;
}else{
return false;
}
}
function checkWhy(inputs){
var state = inputs.validity;
var msg = "";
switch(true){
case state.valueMissing:
msg='内容不能为空!';
break;
case state.patternMismatch:
msg='内容格式错误1!';
break;
case state.typeMismatch:
msg='内容格式错误!';
break;
case state.valid:
msg='√';
break;
}
return msg;
}
for(var i=0;i<inps.length-1;i++){
inps[i].onblur = function(){
for(var j=0;j<inps.length-1;j++){
if(this==inps[j]){
ems[j].innerHTML = checkWhy(inps[j]);
}
}
}
}
sub.onclick = function(){
var isok = true;
// console.log(inps[0].validity.valid)
for(var i=0;i<inps.length-1;i++){
if(success(inps[i])){
isok=isok&&true;
}else{
isok=isok&&false;
}
}
if(isok==true){
alert("注册成功")
}else{
error();
event.preventDefault();
}
}
function error(){
alert("注册失败");
// ....
}
</script>
</html>
网友评论