未做css样式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="rag">
<form id="reg" name="form1" action="a.php" method="post" onsubmit="return checknull();"> //避免提交空数据
<label>用户名:<input id="user" name="user" type="text"><span></span></label><br/>
<label>密码:<input id="pwd" name="pwd" type="password"><span></span></label><br/>
<label>确认密码:<input id="pwd2" name="pwd2" type="password"><span></span></label><br/>
<label>手机号码:<input id="tel" name="tel" type="text"><span></span></label><br/>
<label>电子邮箱:<input id="email" name="email" type="text"><span></span></label><br/>
<label><button id="sub" name="sub" type="submit">提交</button> <button id="res" type="reset">重置</button></label>
</form>
</div>
<script language="javascript">
var list=document.getElementById('rag');
list.addEventListener('focusout',function(event){
event=event||window.event;
var target=event.target||event.srcElement;
switch(target.id){ //选择每个事件目标ID,判断是那个元素,然后再做筛选
case "user":
if(target.value.trim()==''){
target.focus();
target.onfocusout=null;
target.style.backgroundColor="red";
target.nextElementSibling.innerHTML='用户名不能为空';
}else if(!/^\w*$/.test(target.value.trim())){
target.focus();
target.style.backgroundColor="red";
target.nextElementSibling.innerHTML='只能是数字或字母';
}else if(target.value.trim().length<4||target.value.trim.lenght>13){
target.focus();
target.style.backgroundColor='red';
target.nextElementSibling.innerHTML='请填写4-13个字符';
}else{
target.style.backgroundColor='white';
target.nextElementSibling.innerHTML='正确';
}
break;
case "pwd":
if(target.value.trim()==''){
target.focus();
target.style.backgroundColor="red";
target.nextElementSibling.innerHTML='密码不能为空';
}else if(target.value.length<4||target.value.length>16){
target.focus();
target.style.backgroundColor='red';
target.nextElementSibling.innerHTML='字符在4-15之间';
}else if(/^(\d*|[a-z]*)$/.test(target.value.trim())){
target.focus();
target.style.backgroundColor='red';
target.nextElementSibling.innerHTML='密码不能纯数字或字母';
}else{
target.style.backgroundColor='white';
target.nextElementSibling.innerHTML='正确';
}
break;
case 'pwd2':
if(target.value.trim()==''){
target.focus();
target.style.backgroundColor="red";
target.nextElementSibling.innerHTML='密码不能为空';
}else if(target.value.trim()!=document.getElementById('pwd').value.trim()){
target.focus();
target.style.backgroundColor='red';
target.nextElementSibling.innerHTML='两次密码不一致';
}else{
target.style.backgroundColor='white';
target.nextElementSibling.innerHTML='正确';
}
break;
}
});
function checknull(){ //避免提交空数据
var content=document.getElementById('reg');
if(content['user'].value==''||content['pwd'].value==''||content['pwd2'].value==''||content['tel'].value==''||content['email'].value==''){
alert('内容不能为空');
return false;
}
}
</script>
</body>
</html>