表单验证用onblur(失去焦点事件)实现

时间:2021-08-06 08:31:47
<body>
<script type="text/javascript" charset="utf-8">
function check(name,reg,spanId,okInfo,errorInfo){
var flag;
var val = document.getElementsByName(name)[0].value;
var oSpanNode = document.getElementById(spanId);
if(reg.test(val)){
oSpanNode.innerHTML = okInfo.fontcolor("green");
flag = true;
}else{
oSpanNode.innerHTML = errorInfo.fontcolor("red");
flag = false;
}
return flag;
}
//表单总校验
function checkForm(){
if(checkUser()&&checkPassword()&&checkRspassword()&&checkMail())
return true;
return false;
alert(checkUser()+"--"+checkPassword()+"--"+checkRspassword()+"--"+checkMail());
}
//校验用户名
function checkUser(){
//定义正则表达式,a-z,长度为4,忽略大小写
var reg = new RegExp("^[a-z]{4}$","i");
check("username",reg,"namespan","正确","错误");
}
//校验密码
function checkPassword(){
var reg = new RegExp("^[a-z]{4}$","i");
check("password",reg,"passwordspan","正确","错误");
}

//校验确认密码
function checkRspassword(){
var flag;
//获取确认密码框里内容
var rspassword = document.getElementsByName("repassword")[0].value;
//获取密码框里内容
var password = document.getElementsByName("password")[0].value;
var oRepasswordSpan = document.getElementById("repasswordspan");
if (rspassword == password) {
oRepasswordSpan.innerHTML = "正确".fontcolor("green");
flag = true;
}
else {
oRepasswordSpan.innerHTML = "错误".fontcolor("red");
flag = false;
}
return flag;
}

//校验邮箱
function checkMail(){
var reg = new RegExp("^\\w+@\\w+(\\.\\w{2,3})*\\.\\w{2,3}$");
check("mail",reg,"mailspan","正确","错误");
}

</script>
<!--onsubmit点击提交时发生的事件,记得加return!!!-->
<form id="userInfo" onsubmit="return checkForm()">
<!--onblur 失去焦点事件.-->
用户名称<input type="text" name="username" onblur="checkUser()">


用户密码<input type="text" name="password" onblur="checkPassword()">
<span id="passwordspan"></span><br/>

确认密码<input type="text" name="repassword" onblur="checkRspassword()">
<span id="repasswordspan"></span><br/>

邮件地址<input type="text" name="mail" onblur="checkMail()">
<span id="mailspan"></span><br/>

<input type="submit" value="submit" ><br/>
</form>

<!--自定义提交按钮-->
<input type="button" value="提交" onclick="mySubmit()">
</body>
</html>
代码有一些不完善之处,待修改。