js實現表單實時驗證做出提示
阿新 • • 發佈:2019-01-23
對於有很多填寫專案的表單,我們可能更希望在使用者沒有填寫時或填寫出錯時,就即時顯示提示,而不是等到提交時才進行驗證。
html程式碼:
js控制程式碼:<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Register</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> <style type="text/css"> body{margin:0;padding: 0;} .login{position:relative;margin:100px auto;padding:50px 20px;width: 350px;height: 200px;border:1px solid #333;} .login legend{font-weight: bold;color: green;text-align: center;} .login label{display:inline-block;width:130px;text-align: right;} .btn{height: 30px;width:100px;padding: 5px;border:0;background-color: #00dddd;font-weight: bold;cursor: pointer;float: right;} input{height: 20px;width: 170px;} .borderRed{border: 2px solid red;} img{display: none;} </style> </head> <body> <div class="login"> <form name="form" method="post" action="register.php" > <p><label for="name">UserName: </label> <input type="text" id="name" > <p id="titleNull" style="display:none;"><font style="color:red;">不可為空</font></p> </form> </div> </body> </html>
當不填寫內容,滑鼠離開輸入框時,onblur事件被觸發,即顯示提示文字和對應的輸入框邊框顏色變為紅色:<script type="text/javascript"> function hasClass(obj,cls){ // 判斷obj是否有此class return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); } function addClass(obj,cls){ //給 obj新增class if(!this.hasClass(obj,cls)){ obj.className += " "+cls; } } function removeClass(obj,cls){ //移除obj對應的class if(hasClass(obj,cls)){ var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); obj.className = obj.className.replace(reg," "); } } function checkName(name){ //驗證name if(name != ""){ //不為空則正確 removeClass(ele.name,"borderRed"); //移除class,使原來的紅色邊框變為正常顏色 document.getElementById("titleNull").style.display = "none"; //不顯示提示資訊 return true; }else{ //若為空 addClass(ele.name,"borderRed"); //新增class,使輸入框變紅 document.getElementById("titleNull").style.display = ""; //顯示提示資訊 return false; } } var ele = { name: document.getElementById("name") }; ele.name.onblur = function(){ //name失去焦點則檢測 checkName(ele.name.value); } </script>
填入內容後則提示消失: