7、js使用正则表达式验证

时间:2023-02-28 17:14:38
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>正则表达式实现表单验证</title> </head> <body> <fieldset style="width:400px;">
<legend>Xxx网站注册</legend> <table>
<tr>
<td>用户名:</td>
<td><input type="text" id="user"/><span></span></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" id="pwd" onblur="pwdBlur()" onfocus="pwdFocus()"/><span></span></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="password" id="repwd"/><span></span></td>
</tr>
<tr>
<td>邮箱:</td>
<td><input type="text" id="email"/><span></span></td>
</tr>
<tr>
<td><input type="submit" value="注册"/></td>
<td><input type="reset" value="重置"/></td>
</tr> </table> </fieldset> <script type="text/javascript">
function pwdFocus(){ var pwd=document.getElementById("pwd");
pwd.style.border="1px blue solid";
pwd.nextSibling.innerHTML="密码长度必须为6到12";
}
function pwdBlur(){
var pwd=document.getElementById("pwd");
//获取value属性值方式1
//var pwdval=pwd.getAttribute("value"); //获取value属性值方式2
var pwdval=pwd.value;
var reg=/^[a-zA-Z0-9]{6,12}$/;
if(reg.test(pwdval)==false){
pwd.style.border="1px red solid";
pwd.nextSibling.innerHTML="密码长度必须为6到12";
}else{
pwd.style.border="1px green solid";
pwd.nextSibling.innerHTML="密码可用";
} }
</script>
</body>
</html>