解惑(2)javascript 判斷使用者輸入文字框是否為空
阿新 • • 發佈:2018-12-01
舉個之前寫的例子
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>註冊</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"> <link rel="stylesheet" href="css/basic.css"/> <link href="css/login.css" rel="stylesheet" type="text/css"> </head> <body> <div class="mr-tabs" id="doc-my-tabs"> <ul class="mr-tabs-nav mr-nav mr-nav-tabs mr-nav-justify"> <li class="mr-active"><a href="">註冊</a></li> </ul> <div class="mr-tabs-bd"> <div class="mr-tab-panel mr-active"> <form method="post"> <div class="user-email"> <label for="email"><i class="mr-icon-envelope-o"></i></label> <input type="email" name="" id="email" placeholder="請輸入郵箱賬號"> </div> <div class="user-pass"> <label for="password"><i class="mr-icon-lock"></i></label> <input type="password" name="" id="password" placeholder="設定密碼"> </div> <div class="user-pass"> <label for="passwordRepeat"><i class="mr-icon-lock"></i></label> <input type="password" name="" id="passwordRepeat" placeholder="確認密碼"> </div> <div class="user-pass"> <label for="passwordRepeat"><i class="mr-icon-mobile"></i><span style="color:red;margin-left:5px">*</span></label> <input type="text" name="" id="tel" placeholder="請輸入手機號"> </div> </form> <div class="login-links"> <label for="reader-me"> <input id="reader-me" type="checkbox"> 點選表示您同意商城《服務協議》 </label> <a href="login.html" class="mr-fr">登入</a> </div> <div class="mr-cf"> <input type="submit" name="" onclick="mr_verify()" value="註冊" class="mr-btn mr-btn-primary mr-btn-sm mr-fl"> </div> </div> </div> </div> </body> <script> function mr_verify(){ //獲取表單物件 var email=document.getElementById("email"); var password=document.getElementById("password"); var passwordRepeat=document.getElementById("passwordRepeat"); var tel=document.getElementById("tel"); //驗證專案是否為空 if(email.value==='' || email.value===null){ alert("郵箱不能為空!"); return; } if(password.value==='' || password.value===null){ alert("密碼不能為空!"); return; } if(passwordRepeat.value==='' || passwordRepeat.value===null){ alert("確認密碼不能為空!"); return; } if(tel.value==='' || tel.value===null){ alert("手機號碼不能為空!"); return; } if(password.value!==passwordRepeat.value ){ alert("密碼設定前後不一致!"); return; } //驗證郵件格式 apos = email.value.indexOf("@") dotpos = email.value.lastIndexOf(".") if (apos < 1 || dotpos - apos < 2) { alert("郵箱格式錯誤!"); } else { alert("郵箱格式正確!"); } //驗證手機號格式 if(isNaN(tel.value)){ alert("手機號請輸入數字!"); return; } if(tel.value.length!==11){ alert("手機號是11個數字!"); return; } alert('註冊成功!'); } </script> </html>