<html>
<head>
<script src="check.js"></script>
<style>
span{
font-size:12px;
}
.stats1{
color:#aaa; <!-- 默认灰色 -->
}
.stats2{
color:#000;
}
.stats3{
color:red;
}
.stats4{
color:green;
}
</style>
</head>
<body>
<form action="" method="" onsubmit="return regs('submit')">
username:<input type="text" name="username" value="">
<span class="stats1">请输入用户名</span><br/>
password:<input type="password" name="password" value="">
<span class="stats1">请输入密码</span><br/>
repass:<input type="password" name="repass" value="">
<span class="stats1">请再次输入密码</span></br/>
email:<input type="text" name="email" value="">
<span class="stats1">请输入邮箱</span><br/>
other:<input type="text" name="other" value="">
<span class="stats1">请输入其他</span><br/>
<input type="submit" name="sub" value="submit">
</form>
</body>
</html>
//页面加载完自动调用
onload=regs;
//一个函数,可以使用onsubmit调用,也可以使用onload调用
function regs(subm){//我们直接提交表单不会验证,怎么解决呢?我们需要让函数进行判断,直接点击提交的时候得到一个信号,所有验证都执行,使用参数
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];
var other=document.getElementsByName("other")[0];
//为了省代码,使用下一个同胞获取span
//alert(username.nextSibling.nodeName);/前面这种方式有可能控件后面是空格或者图片,所以我们使用一个小算法得到span
//alert(gspan(username).nodeName);
check(username,"用户名的长度要在3-20之间",function(val){
//if(val.match(/^S+$/) && val.length>=3 &&username.value.length<=20){
if(val.match(/^S{3,20}$/)){
return true;
}else{
stat=false;
return false;
}
},subm);
check(password,"密码必须在6-20位之间",function(val){
//if(val.match(/^S+$/) && val.length>=6 &&val.length<=20){
if(val.match(/^S{6,20}$/)){
return true;
}else{
stat=false;
return false;
}
},subm);
check(repass,"确认密码要和上面一致,规则也要相同",function(val){
//if(val.match(/^S+$/) && val.length>=6 &&val.length<=20 && val==password.value ){
if(val.match(/^S{3,20}$/) && val==password.value ){
return true;
}else{
stat=false;
return false;
}
},subm);
check(email,"要按邮箱规则输入",function(val){
if(val.match(/w+@w+.w+/)){
return true;
}else{
stat=false;
return false;
}
},subm);
return stat;
}
function gspan(cobj){//找到下一个span
while(true){
if(cobj.nextSibling.nodeName!="SPAN"){
cobj=cobj.nextSibling;
}else{
return cobj.nextSibling;
}
}
}
/*
通用检查方法:
第一个参数:obj,用来检查的对象
第二个参数:info,用来检查的提示信息
第三个参数:fun,用来检查值是否按条件输入
第四个参数:subm,状态判定,分清是点击提交还是失去焦点
*/
function check(obj,info,fun,subm){
var sp=gspan(obj);
obj.onfocus=function(){//得到焦点提示
//var sp=gspan(username);
sp.innerHTML=info
sp.className="stats2";
}
obj.onblur=function(){
//if(username.value.match(/^S+$/) && username.value.length>=3 &&username.value.length<=20){
if(fun(this.value)){
sp.innerHTML="输入正确";
sp.className="stats4";
}else{
sp.innerHTML=info;
sp.className="stats3";
}
}
if(subm=="submit"){
obj.onblur();
}
}