<script type="text/javascript">
function testCode(){
var code=Math.floor(Math.random()*9000+1000);
var span=document.getElementById("code");
span.innerHTML=code;
}
</script>
form表单的封装校验
<script type="text/javascript">
function testSub(){
return testField("pwd",/^[a-z]\w{5,7}$/);
}
//封装校验:相同的保留,不同的传参
function testField(id,reg){
//获取用户数据
var inp=document.getElementById(id);
var va=inp.value;
var alt=inp.alt;
//创建校验规则
//获取span对象
var span=document.getElementById(id+"Span");
//开始校验
if(va==""||va==null){
//输出校验结果
span.innerHTML=alt+"不能为空";
span.style.color="red";
return false;
}else if(reg.test(va)){
span.innerHTML=alt+"ok";
span.style.color="green";
return true;
}else{
span.innerHTML=alt+"不符合规则";
span.style.color="red";
return false;
}
}
function testAgree(){
document.getElementById("sub").disabled=!document.getElementById("che").checked;
}
function testOnsubmit(){
return testSub();
}
</script>
<form action="#" method="get" onsubmit="return testOnsubmit()">
<input type="text" name="pwd" id="pwd" value="" onblur="testSub()" alt="密码"/>
<span id="pwdSpan"></span><br/>
<br /><br />
<input type="checkbox" name="che" id="che" onclick="testAgree()"/>是否同意本公司协议
<input type="submit" name="sub" id="sub" value="提交" disabled="disabled"/>
</form>