<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>表单验证</title>
<style type="text/css">
tr{
line-height: 50px;
}
input{
height: 30px;
width: 300px;
outline: none;
}
button{
height: 30px;
width: 300px;
}
</style>
</head>
<body>
<form action="#" method="" id="myForm">
<table>
<tbody>
<tr>
<td>用户名</td>
<td><input type="" name="" id="userName" value="" /></td>
<td id="userNameInfor"></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="" name="" id="email" value="" /></td>
<td id="emailInfor"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="" id="pw" value="" /></td>
<td id="pwInfor"></td>
</tr>
<tr>
<td>确认密码</td>
<td><input type="password" name="" id="repw" value="" /></td>
<td id="repwInfor"></td>
</tr>
<tr>
<td></td>
<td><button type="">提交</button></td>
<td></td>
</tr>
</tbody>
</table>
</form>
<script type="text/javascript">
//创建自调用函数--------------
(function(){
//验证用户名-----------------------
const userName=document.querySelector('#userName');
const userNameInfor=document.querySelector('#userNameInfor');
userName.onblur=getUserName;
//验证邮箱-------------------------
const email=document.querySelector('#email');
const emailInfor=document.querySelector('#emailInfor');
email.onblur=getEmail;
//验证密码-----------------------
const pwd=document.querySelector('#pw');
const pwInfor=document.querySelector('#pwInfor');
pwd.onblur=getPwd;
//确认密码
const repw=document.querySelector('#repw');
const repwInfor=document.querySelector('#repwInfor');
repw.onblur=rePw;
//给form添加onsubmit事件,如果返回true就会提交,否则就不会提交数据
const myForm=document.querySelector('#myForm');
myForm.onsubmit=function(){
return getUserName()&& getEmail()&&getPwd()&&rePw();
}
//用户名封装
function getUserName(){
let str=userName.value;
const reg=/^\w{4,12}$/;
//判断输入用户名是否合规------------
if(str.match(reg)){
userNameInfor.innerHTML='用户名可用';
userNameInfor.style.color='green';
return true;
}else{
userNameInfor.innerHTML='用户名不可用';
userNameInfor.style.color='red';
}
}
//邮箱封装
function getEmail(){
const reg=/^[\w-]+@[\w-]+(\.[\w-]+){1,3}$/
if(email.value.match(reg)){
emailInfor.innerHTML='邮箱可用';
emailInfor.style.color='green';
return true;
}else{
emailInfor.innerHTML='邮箱不可用';
emailInfor.style.color='red';
return false;
}
}
//密码封装
function getPwd(){
if(pwd.value.length>6&&pwd.value.length<18){
pwInfor.innerHTML='密码可用'
pwInfor.style.color='green';
return true;
}else{
pwInfor.innerHTML='密码不可用'
pwInfor.style.color='red';
return false;
}
}
//验证密码封装
function rePw(){
if(repw.value===pwd.value){
repwInfor.innerHTML='密码一致';
repwInfor.style.color='green';
return true;
}else{
repwInfor.innerHTML='密码不一致';
repwInfor.style.color='red';
return false;
}
}
}())
</script>
</body>
</html>
09-26