方法一:
使用css的required屬性
<input type="" required="required" name="" id="" value="" />
方法二:
使用JS代碼示例,注意事項:form要加上onSubmit事件,form.xx.vlaue要在表單中對應name
<script type="text/javascript"> function beforeSubmit(form){ if(form.username.value==''){ alert('用戶名不能為空!'); form.username.focus(); return false; } if(form.password.value==''){ alert('密碼不能為空!'); form.password.focus(); return false; } if(form.password.value.length<6){ alert('密碼至少為6位,請重新輸入!'); form.password.focus(); return false; } if(form.password.value!=form.password2.value) { alert('你兩次輸入的密碼不一致,請重新輸入!'); form.password2.focus(); return false; } return true; } </script> <fieldset> <legend>用戶注冊</legend> <form method="post" name="form" action="user.do?method=register" onSubmit="return beforeSubmit(this);"> <table border="1" width="100%" cellspacing="0" cellpadding="0"> <tr><td><label>用戶名:<input type="text" name="username" value=""></label></td></tr> <tr><td><label>密 碼:<input type="password" name="password" value=""></label></td></tr> <tr><td><label>重復密碼:<input type="password" name="password2" value=""></label></td></tr> <tr><td><input value="注冊" type="submit"> <input type="reset" value="重置"></td></tr> </table> </form> </fieldset>
方法三:
使用jQuery方法(通過class驗證),需要引用jquery.min.js
優勢:
1:為input添加class,名字可以隨意設置,但每個input需要保持一致,本章案例calss設置為noNull。(若input已有class屬性,可直接加到其后)
2:為input添加一個屬性,用來后期通過jquery獲取該字段,用作提示語。本章案例提示屬性為notNull。
3:通過jQuery遍歷頁面中所有calss為noNull的表單,驗證其是否為空,若為空,通過獲取notNull的字段,進行為空提示。
具體如何設置,請參照下面的案例。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> </head> <body> <form> <!-- input --> <div> 姓名: <input type="text" name="name" notNull="姓名" class="form-control noNull"> </div> <br> <!-- radio --> <div> 性別: 男<input type="radio" name="sex" value="0" class="noNull" notNull="性別"> 女<input type="radio" name="sex" value="1" > </div> <br> <!-- select --> <div> 年齡: <select name="age" class="noNull" notNull="年齡"> <option value ="">請選擇</option> <option value ="1">1</option> <option value ="2">2</option> </select> </div> <br> <!-- checkbox --> <div> 興趣: 打球<input type="checkbox" name="hobby" value="1" class="noNull" notNull="興趣"> 唱歌<input type="checkbox" name="hobby" value="2"> 跳舞<input type="checkbox" name="hobby" value="3"> </div> <br> <button type="button" class="btn-c" onclick="bubmi()">保存</button> </form> <script src="jquery-1.9.1.min.js"></script> <script type="text/javascript"> function bubmi(){ $(".noNull").each(function(){ var name = $(this).attr("name"); if($(this).val()==""){ alert($(this).attr('notNull')+"不能為空");return false; } if($(this).attr("type")=="radio"){ if ($("input[name='"+name+"']:checked").size() < 1){ alert($(this).attr('notNull')+"不能為空!"); return false; } } if($(this).attr("type")=="checkbox"){ if ($('input[name="'+name+'"]:checked').size() < 1){ alert($(this).attr('notNull')+"不能為空!"); return false; } } }) } </script> </body> </html>