基於Jquery Validate 的表單驗證

基於Jquery Validate 的表單驗證

  jquery.validate.js是jquery下的一個驗證插件,運用此插件咱們能夠很便捷的對錶單元素進行格式驗證。javascript

  在講述基於Jquery Validate的表單驗證前,咱們先回顧一下基礎純JS的表單驗證。css

一、回顧基於JS的表單驗證

  咱們先寫一個簡單的驗證郵箱、手機號的表單,頁面代碼以下:html

 1 <form action="XXXX.action"  method="post" onsubmit="return checkNull();">
 2   <p>
 3     <span class="pSpan">郵 箱:</span>
 4     <input type="text" id="userMail" maxLength="100" onclick="clearSpan2(this,'span7')" onchange="check(this,2,'span7')" />
 5     <span id="span7" style="color: red; font-size: 13px;"></span>
 6   </p>
 7   <p>
 8     <span class="pSpan">手機號:</span>
 9     <input type="text" id="userPhone" onchange="check(this,3,'span8')" onclick="clearSpan2(this,'span8')" />
10     <span id="span8" style="color:red;font-size:13px;"></span>
11   </p>
12   <p>
13     <input type="submit" value="確認" />
14     <input type="reset" value="重置" onclick="clearSpan()" />
15    </p>
16 </form> 

 JS代碼以下:java

 1 function getObj(id){
 2      return document.getElementById(id);
 3 }
 4 
 5 /* 檢查輸入信息是否爲空*/
 6 function checkNull(){
 7     if(getObj("userMail").value!=""){
 8         check(check(getObj("userMail"),2,"span7"));
 9     }else{
10         getObj("span7").innerHTML="";
11     }
12     if(getObj("userPhone").value!=""){
13         check(check(getObj("userPhone"),3,"span8"));
14     }else{
15         getObj("span8").innerHTML="";
16     }
17     if(getObj("span7").innerHTML!=""||getObj("span8").innerHTML!=""){ //判斷提示信息是否爲空     
18         return false;
19     }
20     return true;
21 }
22 /* 清楚驗證提示信息 */
23 function clearSpan(){
24     getObj("span7").innerHTML="";
25     getObj("span8").innerHTML="";
26  }
27  
28 /* 若未輸入信息,則根據id清除提示信息*/   
29 function clearSpan2(id,spanId){
30     if(id.value==""){
31        getObj(spanId).innerHTML="";    
32     }
33 }
34 
35 /* 顯示格式錯誤提示信息 */
36 function check(str, flag, spanId) {
37     var span = getObj(spanId);
38     switch (flag) {
39     case 2:// 郵箱
40         if (str.value!=""&&checkByRegExp(str.value, 2) == false) {
41             span.innerHTML = "填寫的郵箱格式不正確!";
42             str.value = "";
43         } else {
44             span.innerHTML = "";
45         }
46         break;
47 
48     case 3:// 手機號
49         if (str.value!=""&&checkByRegExp(str.value, 3) == false) {
50             span.innerHTML = "填寫的手機號碼格式不正確!";
51             str.value = "";
52         } else {
53             span.innerHTML = "";
54         }
55         break;
56     }
57     
58 }
 1 // 驗證數據格式
 2 function checkByRegExp(str, flag) {
 3   switch (flag) {
 4   case 2:
 5     var reg = new RegExp(/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/);
 7     return reg.test(str);// 郵箱格式
 8     break;
 9   case 3:
11     var reg = new RegExp(/^0?(13[0-9]|15[012356789]|18[0-9]|14[57])[0-9]{8}$/);
13     return reg.test(str);// 手機號格式
14     break;
15   }
16 }

  採用傳統的JS驗證時,咱們不只要在數據輸入格式錯誤時進行提示,在表單提交前還要再次進行格式驗證。本例子,採用判斷提示信息是否爲空,來斷定數據輸入格式是否正確。這樣的表單驗證操做繁瑣,效率低下。jquery

二、對Jquery Validate 簡單介紹

  (本介紹內容引用自:http://blog.csdn.net/zzq58157383/article/details/7718352,此文詳細介紹了Jquery Validate 插件的使用。)ajax

  最常使用JavaScript的場合就是表單的驗證,而jQuery做爲一個優秀的JavaScript庫,也提供了一個優秀的表單驗證插件----Validation。Validation是歷史最悠久的jQuery插件之一,通過了全球範圍內不一樣項目的驗證,並獲得了許多Web開發者的好評。做爲一個標準的驗證方法庫,Validation擁有以下特色:app

  1.內置驗證規則: 擁有必填、數字、Email、URL和信用卡號碼等19類內置驗證規則dom

  2.自定義驗證規則: 能夠很方便地自定義驗證規則async

  3.簡單強大的驗證信息提示: 默認了驗證信息提示,並提供自定義覆蓋默認的提示信息的功能post

  4.實時驗證: 可能經過keyup或blur事件觸發驗證,而不單單在表單提交的時候驗證

三、使用Jquery Validate 插件(簡單的重置密碼功能)

  一、引用引入jQuery庫和Validate插件

1 <script type="text/javascript" src="../jquery-ui-1.9.0/jquery-1.8.2.min.js"></script>
2 <script type="text/javascript" src="../jquery-validation-1.10.0/dist/jquery.validate.js"></script>

  下載連接:http://jquery.com/

  二、使用實例

  本示例驗證項爲原密碼、新密碼、確認密碼,其中原密碼的驗證須要發送至後臺進行驗證(AJAX),並根據返回值判斷其輸入是否正確。新密碼、再次輸入密碼數據的驗證就直接使用validate插件提供的功能便可完成,而原密碼的驗證須要咱們使用 jQuery.validator.addMethod方法創建一個新的驗證方式。

 <body>
    <form action="XXXX.action" method="post" id="form1">
        <table width="100%" cellpadding="0" cellspacing="0" style="border-collapse: collapse;font-size: 12px;">
            <tr height="40px">
                <td width="15%" align="right">原密碼:</td>
                <td>
                    <input type="password" id="oldPassword" name="oldPassword" style="width: 60%;height:30px;line-height:30px; " />
                </td>
            </tr>
            <tr height="40px">
                <td width="15%"  align="right">新密碼:</td>
                <td>
                    <input type="password" id="newPassword" name="newPassword" style="width: 60%;height:30px;line-height:30px;" />
                </td>
            </tr>
            <tr height="40px">
                <td width="15%"  align="right">確認密碼:</td>
                <td>
                    <input  type="password"  id="rePassword" name="rePassword" style="width: 60%;height:30px;line-height:30px;" />
                </td>
            </tr>
            <tr height="40px">
                <td colspan="2"></td>
            </tr>
            <tr height="40px">
            <td></td>
            <td>
                <div style="width:15%;float:left;">&nbsp;</div>
                <div id="save1" style="width: 71px;height: 23px;text-align: center;line-height: 23px;font-size: 14px;color: white;float: left;">保存</div>
         <div style="width:50px;float:left;">&nbsp;</div> <div id="reset1" style="width: 71px;height: 23px;;text-align: center;line-height: 23px;font-size: 14px;color: white;float: left;">重置 </div> </td> </tr> </table> </form> </body> <script type="text/javascript"> $("#reset1").click(function(){ $("#form1")[0].reset(); }); jQuery.validator.addMethod("isPwd", function(value, element) { var result = false; $.ajax({ url : "XXXX.action?v=" + Math.random(), type : "post", //數據發送方式 dataType : "text", //接受數據格式 async : false, data : { oldPassword : $("#oldPassword").val() }, success : function(data, textStatus) { result = data == "T"; } }); return this.optional(element) || (result); }, ""); $(function() { $("#form1").validate({ rules : { "oldPassword" : { required : true, isPwd:true }, "newPassword" : { required : true, minlength : 3 }, "rePassword" : { required : true, minlength : 3, equalTo : "#newPassword" } }, messages : { "oldPassword" : { required : "<span style='color:red;'>請輸入當前使用密碼</span>", isPwd : "<span style='color:red;'>請輸入正確的密碼</span>" }, "newPassword" : { required : "<span style='color:red;'>請輸入您的新密碼</span>", minlength : "<span style='color:red;'>確認密碼不能小於3個字符</span>" }, "rePassword" : { required : "<span style='color:red;'>請輸入確認密碼", minlength : "<span style='color:red;'>確認密碼不能小於3個字符</span>", equalTo : "<span style='color:red;'>兩次輸入密碼不一致</span>" } }, /* 設置驗證觸發事件 */ focusInvalid : false, onkeyup : false, /* 設置錯誤信息提示DOM */ errorPlacement : function(error, element) { error.appendTo(element.parent()); } }); $("#save1").click(function() { $("#form1").submit(); }); }); </script> </html>

   使用Validate插件後,咱們可直接根據表單元素的id或name值進行表單驗證操做,而沒必要在表單元素內一些onclick、onchange事件,這使得頁面更加乾淨、簡潔,也使得咱們的表單驗證操做更一目瞭然。

  新技巧get√!!!over…

注:貼一個Email輔助輸入JS,有興趣的能夠看一下

 1 /*==================email 輔助輸入====================*/
 2 var xfId,totalid,emailafter,emailbefor;
 3 var cenPress = false;
 4 /*
 5  * email2輸入框輸入文字時觸發並顯示email輔助輸入下拉框
 6  */
 7 $(document).ready(function(){    
 8     $("#email2").focus(function(){ //email2得到焦點,dom寫入email輔助輸入層
 9         $("#myEmail2").remove();//移除歷史輔助信息
10     $(this).after("<div id='myEmail2' class='form-control' style='width:200px; height:auto; background:#fff; color:#6B6B66; position:absolute; left:"+$(this).get(0).offsetLeft+"px; top:"+($(this).get(0).offsetTop+$(this).height()+2)+"px; border:1px solid #ccc;z-index:5; '></div>");
11         if($("#myEmail2").html()==true){
12             $("#myEmail2").css("display","block");//顯示
13             $(".newEmail").css("width",$("#myEmail2").width());//改變寬度
14             cenPress = true;
15         } else {
16              $("#myEmail2").css("display","none");//隱藏
17              cenPress = false;
18         }        
19     }).keyup(function(){ //email2文本框輸入時,觸發,顯示Email輔助輸入
20         var press = $("#email2").val();
21         if(press!=""&&$.trim(press)==""){//判斷是否輸入空格
22             $("#emailSpan").html("<span style='font-size:13px;line-height:30px;color:red;'>請不要輸入空格!</span>");
23         }
24         if ($.trim(press)!=""&& press!=null){//判斷是否輸入空格之外的值
25         var emailText = "";            
26         var emailArray = new Array("@163.com","@qq.com","@126.com","@sina.com","@gmail.com","@yahoo.com","@hotmail.com","@foxmail.com");
27         totalid = emailArray.length;//獲取array長度,並賦值給totalid
28             var emailS = "<div class='newEmail' style='width:200px;overflow:hidden;height:25px;line-height:25px; color:#6B6B66; '>"                 +"<font color='#D33025'>" + press + "</font></div>";
29             if(!(isEmail(press))){
30                 for(var i=0; i<emailArray.length; i++) {
31                     emailText = emailText + "<div class='newEmail' style='width:200px;color:#6B6B66;overflow:hidden;height:25px;"
                  +"line-height:25px;'><font color='#D33025'>" + press + "</font>" + emailArray[i] + "</div>"; 32 } 33 } else { 34 emailbefor = press.split("@")[0];//@前的數據值 35 emailafter = "@" + press.split("@")[1];//@+@後的數據值 36 //循環顯示拼接email輔助提示後的值 37 for(var i=0; i<emailArray.length; i++) { 38 var emailStr = emailArray[i]; 39 if(emailStr.indexOf(emailafter) == 0) { 40 emailText = emailText + "<div class='newEmail' style='width:200px;height:25px;line-height:25px; "
            +"color:#6B6B66; overflow:hidden;'><font color='#D33025'>" + emailbefor + "</font>" + emailArray[i] + "</div>"; 41 } 42 } 43 } 44 45 //顯示email輔助輸入下拉框的數據 46 $("#myEmail2").html(emailS+emailText); 47 if($("#myEmail2").html()){ 48 $("#myEmail2").css("display","block"); 49 $(".newEmail").css("width",$("#myEmail2").width()); 50 cenPress = true; 51 } else { 52 $("#myEmail2").css("display","none"); 53 cenPress = false; 54 } 55 beforepress = press; 56 } 57 //無輸入值不顯示輔助輸入框 58 if (press=="" || press==null){ 59 $("#myEmail2").html(""); 60 $("#myEmail2").css("display","none"); 61 } 62 }); 63 64 65 //鼠標懸浮時顯示高亮效果 66 $(document).on("mouseover",".newEmail",function(){ 67 $(".newEmail").css("background","#FFF"); 68 $(this).css("background","#CACACB"); 69 $(this).focus(); 70 xfId = $(this).index(); 71 }).on("click",".newEmail",function(){ //點擊選中 72 var htmlVal = $(this).html(); 73 htmlVal = htmlVal.replace(/<.*?>/g,""); 74 $("#email2").val(htmlVal); //根據所選內容,替換email2的值 75 $("#myEmail2").remove();//刪除提示層 76 $("#email2").keyup(); 77 }); 78 79 //email選擇文本框失去焦點時刪除層 80 $(document).click(function(){ 81 if(cenPress){ 82 $("#myEmail2").remove(); 83 cenPress = false; 84 if($("#emai2").focus()){ 85 cenPress = false; 86 } 87 } 88 }); 89 }) ; 90 //檢查email郵箱,看是否輸入@ 91 function isEmail(str){ 92 return str.indexOf("@") > 0?true:false; 93 }
相關文章
相關標籤/搜索