js實驗-表單驗證(正則表示式)
阿新 • • 發佈:2018-12-01
<!DOCTYPE html> <html lang="en"> <head> <title>Document</title> </head> <script src="./1.js"></script> <body> <strong>使用者名稱:</strong> <input type="text" id="username" onblur="USN()"> <span id="a"></span><br> <strong>密碼: </strong> <input type="password" id="pwd" onblur="PWD()"><span id="b"></span><br> <strong>確認密碼:</strong> <input type="password" id="confirmpwd"><span id="c"></span><br> <strong>郵件地址:</strong> <input type="text" id="email" onblur="EMAIL()"><span id="d"></span> </body> </html>
JavaScript
function USN() { var x = document.getElementById("username").value; var reg=/^[a-zA-Z]\S+/; if(!reg.test(x)) document.getElementById("a").innerHTML="使用者名稱只能以字母開頭"; else if(x.length < 6 || x.length > 20) document.getElementById("a").innerHTML="使用者名稱長度大於6小於20"; else document.getElementById("a").innerHTML=""; } function PWD() { var x = document.getElementById("pwd").value; var y = document.getElementById("username").value; if(x == y) document.getElementById("b").innerHTML="密碼不能和使用者名稱相同"; else if(x.length < 6 || x.length > 20) document.getElementById("b").innerHTML="密碼長度大於6小於20"; else document.getElementById("b").innerHTML=""; } function EMAIL() { var x = document.getElementById("email").value; var reg = /^\w{1,15}(?:@(?!-))(?:(?:[a-z0-9-]*)(?:[a-z0-9](?!-))(?:\.(?!-)))+[a-z]{2,4}$/; if(!reg.test(x)) document.getElementById("d").innerHTML="請輸入正確的電子郵箱"; else document.getElementById("d").innerHTML=""; }