案例:驗證表單 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> body { background: #ccc; } labe ...
案例:驗證表單
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> body { background: #ccc; } label { width: 40px; display: inline-block; } span { color: red; } .container { margin: 100px auto; width: 400px; padding: 50px; line-height: 40px; border: 1px solid #999; background: #efefef; } span { margin-left: 30px; font-size: 12px; } .wrong { color: red } .right { color: green; } .defau { width: 200px; height: 20px; } .de1 { background-position: 0 -20px; } </style> </head> <body> <div class="container" id="dv"> <label for="qq">Q Q</label><input type="text" id="qq"><span></span><br/> <label>手機</label><input type="text" id="phone"><span></span><br/> <label>郵箱</label><input type="text" id="e-mail"><span></span><br/> <label>座機</label><input type="text" id="telephone"><span></span><br/> <label>姓名</label><input type="text" id="fullName"><span></span><br/> </div> <script src="common.js"></script> <script> //qq的 checkInput(my$("qq"),/^\d{5,11}$/); //手機 checkInput(my$("phone"),/^\d{11}$/); //郵箱 checkInput(my$("e-mail"),/^[0-9a-zA-Z_.-]+[@][0-9a-zA-Z_.-]+([.][a-zA-Z]+){1,2}$/); //座機號碼 checkInput(my$("telephone"),/^\d{3,4}[-]\d{7,8}$/); //中文名字 checkInput(my$("fullName"),/^[\u4e00-\u9fa5]{2,6}$/); //給我文本框,給我這個文本框相應的正則表達式,我把結果顯示出來 //通過正則表達式驗證當前的文本框是否匹配並顯示結果 function checkInput(input,reg) { //文本框註冊失去焦點的事件 input.onblur=function () { if(reg.test(this.value)){ this.nextElementSibling.innerText="正確了"; this.nextElementSibling.style.color="green"; }else{ this.nextElementSibling.innerText="讓你得瑟,錯了吧"; this.nextElementSibling.style.color="red"; } }; } </script> </body> </html>