1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>表单验证</title> 6 <script type="text/javascript"> 7 // 检查两次密码输入是否一致 8 function checkPwdAndRepwd(isEmpty2, isEmpty3){ 9 if (isEmpty2 && isEmpty3) { 10 var pwd = document.getElementById("password").value; 11 var repwd = document.getElementById("re_password").value; 12 var spMsgEl = document.getElementById("re_passwordMsg"); 13 if (pwd == repwd) { 14 spMsgEl.innerHTML=""; 15 return true; 16 } else { 17 spMsgEl.innerHTML="两次密码不一致"; 18 return false; 19 } 20 } else { 21 return false; 22 } 23 } 24 // 检查元素值是否非空 25 function checkNotEmpty(id){ 26 var value = document.getElementById(id).value; 27 var spMsgEl = document.getElementById(id+"Msg"); 28 if (value == "") { 29 spMsgEl.innerHTML = "信息不能为空"; 30 return false; 31 } else { 32 spMsgEl.innerHTML=""; 33 return true; 34 } 35 } 36 // 检查表单 37 function checkForm(){ 38 var flag1 = checkNotEmpty("username"); 39 var flag2 = checkNotEmpty("password"); 40 var flag3 = checkNotEmpty("re_password"); 41 var isEqual = checkPwdAndRepwd(flag2,flag3); 42 var flag4 = checkNotEmpty("nickname"); 43 var flag5 = checkNotEmpty("birthday"); 44 return flag1 && isEqual && flag4 && flag5; 45 } 46 </script> 47 </head> 48 <body> 49 <h2 align="center">新用户注册</h2> 50 <form action="#" method="post" onsubmit="return checkForm()"> 51 <table align="center"> 52 <tr> 53 <td>用户名:</td> 54 <td><input type="text" name="username" id="username"></td> 55 <td><font color="red" size="3"><span id="usernameMsg"></span></font></td> 56 </tr> 57 <tr> 58 <td>密 码:</td> 59 <td><input type="password" name="password" id="password"></td> 60 <td><font color="red" size="3"><span id="passwordMsg"></span></font></td> 61 </tr> 62 <tr> 63 <td>确认密码:</td> 64 <td><input type="password" name="re_password" id="re_password"></td> 65 <td><font color="red" size="3"><span id="re_passwordMsg"></span></font></td> 66 </tr> 67 <tr> 68 <td>昵 称</td> 69 <td><input type="text" name="nickname" id="nickname"></td> 70 <td><font color="red" size="3"><span id="nicknameMsg"></span></font></td> 71 </tr> 72 <tr> 73 <td>生 日:</td> 74 <td><input type="date" name="birthday" id="birthday"></td> 75 <td><font color="red" size="3"><span id="birthdayMsg"></span></font></td> 76 </tr> 77 <tr> 78 <td colspan="3" align="center"> 79 <input type="button" value="注册" /> 80 <input type="submit" value="登录" /> 81 </td> 82 </tr> 83 </table> 84 </form> 85 </body> 86 </html>