简单的表单验证,直接上代码,初学正则,加油加油!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>表单验证</title> </head> <body> <form action="" > <ul> <li>用户账号:<input type="text" id="count" onblur="checkCount()"><span id="countwr"></span></li> <li>真实姓名:<input type="text" id="name" onblur="checkName()"><span id="namewr"></span></li> <li>输入密码:<input type="password" id="password" onblur="checkPassword()"><span id="passwordwr"></span></li> <li>确认密码:<input type="password" id="pdConfirm" onblur="chenckPdconfirm()"><span id="pdConfirmwr"></span></li> </ul> <button type="submit" id="hidden-window-yes" >确定</button> </form> <script> //验证账号 function checkCount() { var exp = /^([0-9]{6})$/; var count = document.getElementById("count").value; var countwr=document.getElementById("countwr"); console.log(exp.test(count)); if(exp.test(count)){ countwr.innerText = "输入正确!"; countwr.style.color="green"; return true; } else { countwr.innerText = "请输入六位数字!"; countwr.style.color="red"; return false; } } //验证姓名 function checkName() { var exp = /^([\u4E00-\u9FA5]+)$/; var name = document.getElementById("name").value; var namewr =document.getElementById("namewr"); console.log(exp.test(name)); if(exp.test(name)) { namewr.innerText = "输入正确!"; namewr.style.color="green"; return true; } else { namewr.innerText = "输入错误!"; namewr.style.color = "red"; return false; } } //验证密码 function checkPassword() { var exp =/^([0-9a-z]{8})$/; var password = document.getElementById("password").value; var passwordwr = document.getElementById("passwordwr"); if(exp.test(password)) { passwordwr.innerText="输入正确!"; passwordwr.style.color="green"; return true; } else{ passwordwr.innerText = "输入错误!"; passwordwr.style.color = "red"; return false; } } //验证确认密码 function chenckPdconfirm() { var password = document.getElementById("password").value; var pdConfirm = document.getElementById("pdConfirm").value; var pdConfirmwr = document.getElementById("pdConfirmwr"); if(password == pdConfirm) { pdConfirmwr.innerText="密码匹配!"; pdConfirmwr.style.color="green"; return true; } else { pdConfirmwr.innerText="密码不匹配!"; pdConfirmwr.style.color="red"; return false; } } </script> </body> </html>
时间: 2024-11-10 07:48:55