<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
span{
display: none;
color: red;
}
</style>
</head>
<body>
<form id="form" method="post" action="http://www.baidu.com">
用户名:<input type="text" name="userName" id="userName" value="" />
<span id="checkText">用户名必须在6-16位,必须以字母开头。不能包含特殊字符
</span>
<span id="checkOk" style="color:green;">ok
</span>
<span id="checkErro">
用户不合法
</span><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
<script type="text/javascript">
var userName=document.getElementById("userName");
var form=document.getElementById("form");
var sub=document.getElementById("sub")
//必须以字母开头,其它的除了特殊字符以外所有的字符,最少六个,最多16个
var reg=/^[a-zA-Z]\w{5,15}$/;
var checkText = document.getElementById("checkText");
var checkOk = document.getElementById("checkOk");
var checkErro = document.getElementById("checkErro");
userName.onfocus=function(){
checkText.style.display="inline-block";
}
userName.onblur=function(){
checkText.style.display="inline-block";
checkUserName();
}
var flag=false;
function checkUserName(){
if(reg.test(userName.value)){
checkErro.style.display="none";
checkOk.style.display="inline-block";
checkText.style.display="none";
flag=true;
}else{
checkErro.style.display="inline-block";
checkOk.style.display="none";
checkText.style.display="none";
flag=false;
}
}
form.onsubmit=function(){
if(flag){
//当正则通过时return true;
return true;
}else{
//当正则不通过时return false;
return false;
}
}
</script>