function getspan(cobj){
while(true){
if(cobj.nextSibling.nodeName!="SPAN")
cobj=cobj.nextSibling;
else
return cobj.nextSibling;
}
}
/*
通用的检测函数
obj:检测的对象
error:检查出错的信息
fun:回调函数,检测输入的值是否符合规则
click:状态,判断是点击提交按钮 还是失去焦点
*/
function check(obj,error,fun,click){
var sp=getspan(obj);
obj.onfocus=function(){
sp.innerHTML=error;
sp.className="stat2";
}
obj.onblur=function(){
if(fun(this.value)){
sp.innerHTML="OK!";
sp.className="stat4";
}else{
sp.innerHTML=error;
sp.className="stat3";
}
}
if(click=="click")
obj.onblur();
}
/*加载页面调用*/
function regs(click){
var stat=true;
var username=document.getElementsByName("username")[0];
var password=document.getElementsByName("password")[0];
var repass=document.getElementsByName("repass")[0];
var email=document.getElementsByName("email")[0];
check(username,"用户名长度必须在6-15位之间",function(val){
if(val.match(/^\S+$/) && val.length>=6 && val.length<=15){
return true;
}else{
stat=false;
return false;
}
},click);
check(password,"密码长度必须在6-10位之间",function(val){
if(val.match(/^\S+$/) && val.length>=6 && val.length<=10){
return true;
}else{
stat=false;
return false;
}
},click);
check(repass,"必须和上面的相同,并且规则也一样",function(val){
if(val.match(/^\S+$/) && val.length>=6 && val.length<=10 && val==password.value){
return true;
}else{
stat=false;
return false;
}
},click);
check(email,"邮箱格式不对",function(val){
if(val.match(/\w+@\w+\.\w/)){
return true;
}else{
stat=false;
return false;
}
},click);
return stat;
}
<head>
<script src="check.js"></script>
<style>
.stat1{
color:#aaa;
}
.stat2{
color:#000;
}
.stat3{
color:red;
}
.stat4{
color:green;
}
</style>
</head>
<body>
<form action="reg.php" method="post" onsubmit="return regs('click');">
username:<input type="text" name="username" value="">
<span class="stat1"></span><br>
password:<input type="text" name="password" value="">
<span class="stat1"></span><br>
repass:<input type="text" name="repass" value="">
<span class="stat1"></span><br>
email:<input type="text" name="email" value="">
<span class="stat1"></span><br>
submit:<input type="submit" name="sub" value="submit">
</form>
</body>
</html>