JS练习-用户名-密码-邮箱格式验证
1、register.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 2 <html> 3 <head> 4 <title>register.html</title> 5 <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 6 <script type="text/javascript" src="js/validateForm.js"></script> 7 </head> 8 <body > 9 <form action="#" method="post" name="myForm"> 10 <table border="1" align="center"> 11 <caption>基于JS的验证</caption> 12 <tr> 13 <th>用户名</th> 14 <td><input type="text" name="username"/></td> 15 </tr> 16 <tr> 17 <th>密码</th> 18 <td><input type="password" name="password"/></td> 19 </tr> 20 <tr> 21 <th>邮箱</th> 22 <td><input type="text" name="email"/></td> 23 </tr> 24 <tr> 25 <td colspan="2" align="center"> 26 <input type="submit" value="提交"/> 27 </td> 28 </tr> 29 </table> 30 </form> 31 </body> 32 </html>
2、validateForm.js
1 function validateForm(){ 2 3 var formElement = document.myForm; 4 // 依次取出用户名和密码 5 var username = formElement.username.value; 6 var password = formElement.password.value; 7 var email = formElement.email.value; 8 // alert("去空格前:"+"#"+username+"#"+":"+password+":"+email+"长度:"+username.length); 9 username = trim(username); 10 password = trim(password); 11 email = trim(email); 12 // alert("去空格后:"+username+":"+password+":"+email+"长度:"+username.length); 13 checkUsername(username); 14 checkPassword(password); 15 checkEmail(email); 16 } 17 // 验证邮箱 18 function checkEmail(email){ 19 var flag = true; 20 if(email.length==0){ 21 flag = false; 22 alert("邮箱不能为空!"); 23 }else if(!/^\w+@\w+(\.\w+)+$/.test(email)){ 24 flag = false; 25 alert("邮箱格式不对"); 26 } 27 return flag; 28 } 29 30 // 验证密码 31 function checkPassword(password){ 32 var flag = true; 33 var formElement = document.myForm; 34 if(password.length == 0){ 35 flag = false; 36 alert("密码不能为空!"); 37 formElement.password.focus(); 38 }else if(!/^[0-9]{6}$/.test(password)){ 39 flag = false; 40 alert("密码必须为6位数字!"); 41 } 42 return flag; 43 } 44 // 验证用户名 45 function checkUsername(username) { 46 var flag = true; 47 var formElement = document.forms[0]; 48 if(username.length == 0){ 49 flag = false; 50 alert("用户名不能为空!"); 51 formElement.username.focus(); 52 }else if(!/^[a-zA-Z0-9]+$/.test(username)){ 53 flag = false; 54 alert("用户名必须为英文数字和下划线和美元符号"); 55 } 56 return flag; 57 } 58 // 自定义去空格函数 59 function trim(s){ 60 s = s.replace(/(^\s*)|(\s*$)/g, "");//去前后空格 61 // s = s.replace(/^\s*$/,""); 62 return s; 63 } 64 window.onload = function(){ 65 var formElement = document.myForm; 66 formElement.onsubmit=validateForm; 67 };
by hacket