JavaScript---通过正则表达式验证表单输入
验证输入的name只能是数字或字母或下划线
js
<script type="text/javascript"> function submitOn(){ var f = document.getElementById("userfrm"); var isValiUserName = false, isValiPassword = false; var userNameStr = f.username.value; var passwordStr = f.pass.value; var rpasswordStr = f.rpass.value; if(userNameStr!="" && userNameStr!=undefined){ //正则表达式验证只能包括字母、数字和下划线字符 var re = new RegExp(/^[a-zA-Z0-9_]+$/,"ig"); //正则表达式验证包括字母、数字或下划线,且长度大于等于5,小于等于10 var re = new RegExp("[a-zA-Z0-9_]{5,10}","ig"); isValiUserName = re.test(userNameStr); //得到用户名true/false的校验结果 } //校验密码 if(passwordStr!="" && passwordStr.length>=6 && passwordStr === rpasswordStr){ isValiPassword = true; } if(isValiUserName==true && isValiPassword==true) return true; return false; } </script>
html
<form id="userfrm" name="userfrm" method="post" action="#"> 登 录 名:<input name="username" type="text"/><br/> 密 码:<input name="pass" type="password"/><br/> 重复密码:<input name="rpass" type="password"/><br> <input type="button" value="提交" onClick="submitOn()"/> </form>