用javascript實(shí)現(xiàn)前端驗(yàn)證的方法:1、創(chuàng)建一個(gè)用戶注冊(cè)的HTML頁(yè)面;2、通過(guò)form表單定義兩個(gè)文本框;3、通過(guò)js代碼“function checkPass(){if(document.getElementById("p").value!=document.getElementById("cp").value){…}”對(duì)文本框內(nèi)容進(jìn)行驗(yàn)證即可。
本教程操作環(huán)境:Windows10系統(tǒng)、javascript1.8.5版本、Dell G3電腦。
怎么用javascript實(shí)現(xiàn)前端驗(yàn)證?
使用Javascript進(jìn)行前端驗(yàn)證:
設(shè)計(jì)簡(jiǎn)單的用戶注冊(cè)頁(yè)面,其中包括“請(qǐng)輸入密碼”和“請(qǐng)?jiān)俅屋斎朊艽a”兩個(gè)文本框
使用Javascript對(duì)“請(qǐng)輸入密碼”和“請(qǐng)?jiān)俅屋斎朊艽a”兩個(gè)文本框的內(nèi)容進(jìn)行驗(yàn)證,如果兩個(gè)文本框的內(nèi)容不一樣則顯示“兩次輸入的密碼不一致!”對(duì)話框。
(1)設(shè)計(jì)簡(jiǎn)單的用戶注冊(cè)頁(yè)面,其中包括“請(qǐng)輸入密碼”和“請(qǐng)?jiān)俅屋斎朊艽a”兩個(gè)文本框;
(2)使用Javascript對(duì)“請(qǐng)輸入密碼”和“請(qǐng)?jiān)俅屋斎朊艽a”兩個(gè)文本框的內(nèi)容進(jìn)行驗(yàn)證,如果兩個(gè)文本框的內(nèi)容不一樣則顯示“兩次輸入的密碼不一致!”對(duì)話框。
先來(lái)看看效果:
<!DOCTYPE html> <html> <script type="text/javascript"> function checkPass(){ if(document.getElementById("p").value!=document.getElementById("cp").value){ document.getElementById("war").style.display = "block"; } } </script> <head> <meta charset="UTF-8"> <title>注冊(cè)</title> <link rel="stylesheet" type="text/css" href="Login.css"/> </head> <body> <div id="login"> <h1>注冊(cè)</h1> <form method="post"> <input type="text" required="required" placeholder="用戶名" name="u"></input> <input type="password" required="required" placeholder="請(qǐng)輸入密碼" name="p" id="p"></input> <input type="password" required="required" placeholder="請(qǐng)?jiān)俅屋斎朊艽a" name="cp" id="cp" onblur="checkPass()"></input> <span id="war" style="display:none"> 兩次密碼的輸入不一致 </span> <button type="submit">登錄</button> </form> </div> </body> </html>
html{ overflow: hidden; font-style: sans-serif; } body{ font-family: 'Open Sans',sans-serif; margin: 0; background-image: url(1.jpg); background-position: 0 -90px; background-size: cover; } #login{ position: absolute; top: 45%; left:50%; margin: -150px 0 0 -150px; width: 300px; height: 300px; } #login h1{ color: #fff; text-shadow:0 0 6px; letter-spacing: 1px; text-align: center; } h1{ font-size: 2em; margin: 0.67em 0; } input{ width: 278px; height: 18px; margin-bottom: 10px; outline: none; padding: 10px; font-size: 13px; color: #fff; text-shadow:0px 0px 0.5px; border-top: 1px solid #312E3D; border-left: 1px solid #312E3D; border-right: 1px solid #312E3D; border-bottom: 1px solid #56536A; border-radius: 4px; background-color: #2D2D3F; } #war{ position:absolute; color:red; margin: 0em 4em; writing-mode: horizontal-tb; font-size: 8px; } .but{ width: 300px; min-height: 20px; margin-top: 20px; display: block; background-color: #4a77d4; border: 2px solid #3762bc; color: #fff; padding: 9px 18px; font-size: 18px; line-height: normal; }
推薦學(xué)習(xí):《JavaScript視頻教程》