表單校驗:創建表單,使用JavaScript+dom為表單添加校驗.
要求:
驗證用戶名稱,必須以字母開頭,長度2-6位之間;
驗證密碼不能為空;
確認密碼不能為空,要與密碼一致;
<!DOCTYPE html> <html> <!-- 表單校驗:創建表單,使用JavaScript為表單添加校驗. 1.驗證用戶名稱,必須以字母開頭,長度2-6位之間. 2.驗證密碼不能為空. 3.確認密碼不能為空,要與密碼一致. --> <head> <meta charset="UTF-8"> <title>Document</title> <script type="text/javascript"> function checkForm() { //獲得用戶名對象 var username = document.getElementById("username"); //---獲得用戶名輸入框中的value值 var usernamevalue = username.value; var Reg = /^[a-zA-Z][-_a-zA-Z0-9]{1,5}/; // JavaScript中的正則與Java的正則略有不同 if (usernamevalue.length >= 2 && usernamevalue.length <= 6 && Reg.test(usernamevalue)) { //為span設置提示語 document.getElementById("usernameSpan").innerHTML = "<font color='green'> 用戶名可用<font>"; } else { document.getElementById("usernameSpan").innerHTML = "<font color='red'> 用戶名必須以字母開頭且長度在2-6之間<font>"; } //獲得密碼value var password = document.getElementById("password").value; if (password == "") { document.getElementById("passwordSpan").innerHTML = "<font color='red'>密碼不能為空</font>"; } else { document.getElementById("passwordSpan").innerHTML = "<font color='green'>密碼可用</font>"; } //獲得確認密碼 var repassword = document.getElementById("repassword").value; if (repassword == password) { document.getElementById("repasswordSpan").innerHTML = "<font color='green'>輸入一致</font>"; } else { document.getElementById("repasswordSpan").innerHTML = "<font color='red'>兩次輸入密碼不一致</font>"; } } </script> </head> <body> <h2>新用戶注冊</h2> <p style="border: 1px solid sandybrown; width: 300px; height: 260px;"> <form action=""> <table cellspacing="15"> <tr> <td>用戶名稱:</td> <td> <input type="text" id="username"> <span id="usernameSpan"></span> </td> </tr> <tr> <td>密  碼:</td> <td> <input type="password" id="password"> <span id="passwordSpan"></span> </td> </tr> <tr> <td>確認密碼:</td> <td> <input type="password" id="repassword"> <span id="repasswordSpan"></span> </td> </tr> </table> </form> </p> <input type="button" value="確認注冊" onclick="checkForm()" /> </body> </html>