jQuery - Validate

jQuery Validate 插件爲表單提供了強大的驗證功能,讓客戶端表單驗證變得更簡單,同時提供了大量的定製選項,知足應用程序各類需求。該插件捆綁了一套有用的驗證方法,包括 URL 和電子郵件驗證,同時提供了一個用來編寫用戶自定義方法的 API。javascript

1.14.0 版本下載地址:http://static.runoob.com/download/jquery-validation-1.14.0.zipphp

導入js庫:

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>

默認校驗規則:

序號 規則 描述
1 required:true 必須輸入的字段。
2 remote:"check.php" 使用 ajax 方法調用 check.php 驗證輸入值。
3 email:true 必須輸入正確格式的電子郵件。
4 url:true 必須輸入正確格式的網址。
5 date:true 必須輸入正確格式的日期。日期校驗 ie6 出錯,慎用。
6 dateISO:true 必須輸入正確格式的日期(ISO),例如:2009-06-23,1998/01/22。只驗證格式,不驗證有效性。
7 number:true 必須輸入合法的數字(負數,小數)。
8 digits:true 必須輸入整數。
9 creditcard: 必須輸入合法的信用卡號。
10 equalTo:"#field" 輸入值必須和 #field 相同。
11 accept: 輸入擁有合法後綴名的字符串(上傳文件的後綴)。
12 maxlength:5 輸入長度最可能是 5 的字符串(漢字算一個字符)。
13 minlength:10 輸入長度最小是 10 的字符串(漢字算一個字符)。
14 rangelength:[5,10] 輸入長度必須介於 5 和 10 之間的字符串(漢字算一個字符)。
15 range:[5,10] 輸入值必須介於 5 和 10 之間。
16 max:5 輸入值不能大於 5。
17 min:10 輸入值不能小於 10。

默認提示:

messages: {
    required: "This field is required.",
    remote: "Please fix this field.",
    email: "Please enter a valid email address.",
    url: "Please enter a valid URL.",
    date: "Please enter a valid date.",
    dateISO: "Please enter a valid date ( ISO ).",
    number: "Please enter a valid number.",
    digits: "Please enter only digits.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "Please enter the same value again.",
    maxlength: $.validator.format( "Please enter no more than {0} characters." ),
    minlength: $.validator.format( "Please enter at least {0} characters." ),
    rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ),
    range: $.validator.format( "Please enter a value between {0} and {1}." ),
    max: $.validator.format( "Please enter a value less than or equal to {0}." ),
    min: $.validator.format( "Please enter a value greater than or equal to {0}." )
}

jQuery Validate提供了中文信息提示包,位於下載包的 dist/localization/messages_zh.js,內容以下:html

(function( factory ) {
    if ( typeof define === "function" && define.amd ) {
        define( ["jquery", "../jquery.validate"], factory );
    } else {
        factory( jQuery );
    }
}(function( $ ) {

/*
 * Translated default messages for the jQuery validation plugin.
 * Locale: ZH (Chinese, 中文 (Zhōngwén), 漢語, 漢語)
 */
$.extend($.validator.messages, {
    required: "這是必填字段",
    remote: "請修正此字段",
    email: "請輸入有效的電子郵件地址",
    url: "請輸入有效的網址",
    date: "請輸入有效的日期",
    dateISO: "請輸入有效的日期 (YYYY-MM-DD)",
    number: "請輸入有效的數字",
    digits: "只能輸入數字",
    creditcard: "請輸入有效的信用卡號碼",
    equalTo: "你的輸入不相同",
    extension: "請輸入有效的後綴",
    maxlength: $.validator.format("最多能夠輸入 {0} 個字符"),
    minlength: $.validator.format("最少要輸入 {0} 個字符"),
    rangelength: $.validator.format("請輸入長度在 {0} 到 {1} 之間的字符串"),
    range: $.validator.format("請輸入範圍在 {0} 到 {1} 之間的數值"),
    max: $.validator.format("請輸入不大於 {0} 的數值"),
    min: $.validator.format("請輸入不小於 {0} 的數值")
});

}));

能夠將該本地化信息文件 dist/localization/messages_zh.js 引入到頁面:java

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>

 

使用方式:

一、將校驗規則寫到控件中jquery

<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/lib/jquery.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/jquery.validate.min.js"></script>
<script src="http://static.runoob.com/assets/jquery-validation-1.14.0/dist/localization/messages_zh.js"></script>
<script>
$.validator.setDefaults({
    submitHandler: function() {
      alert("提交事件!");
    }
});
$().ready(function() {
    $("#commentForm").validate();
});
</script>

<form class="cmxform" id="commentForm" method="get" action="">
  <fieldset>
    <legend>輸入您的名字,郵箱,URL,備註。</legend>
    <p>
      <label for="cname">Name (必需, 最小兩個字母)</label>
      <input id="cname" name="name" minlength="2" type="text" required>
    </p>
    <p>
      <label for="cemail">E-Mail (必需)</label>
      <input id="cemail" type="email" name="email" required>
    </p>
    <p>
      <label for="curl">URL (可選)</label>
      <input id="curl" type="url" name="url">
    </p>
    <p>
      <label for="ccomment">備註 (必需)</label>
      <textarea id="ccomment" name="comment" required></textarea>
    </p>
    <p>
      <input class="submit" type="submit" value="Submit">
    </p>
  </fieldset>
</form>

二、將校驗規則寫到 js 代碼中git

$().ready(function() {
// 在鍵盤按下並釋放及提交後驗證提交表單
  $("#signupForm").validate({
    rules: {
      firstname: "required",
      lastname: "required",
      username: {
        required: true,
        minlength: 2
      },
      password: {
        required: true,
        minlength: 5
      },
      confirm_password: {
        required: true,
        minlength: 5,
        equalTo: "#password"
      },
      email: {
        required: true,
        email: true
      },
      topic: {
        required: "#newsletter:checked",
        minlength: 2
      },
      agree: "required"
    },
    messages: {
      firstname: "請輸入您的名字",
      lastname: "請輸入您的姓氏",
      username: {
        required: "請輸入用戶名",
        minlength: "用戶名必需由兩個字母組成"
      },
      password: {
        required: "請輸入密碼",
        minlength: "密碼長度不能小於 5 個字母"
      },
      confirm_password: {
        required: "請輸入密碼",
        minlength: "密碼長度不能小於 5 個字母",
        equalTo: "兩次密碼輸入不一致"
      },
      email: "請輸入一個正確的郵箱",
      agree: "請接受咱們的聲明",
      topic: "請選擇兩個主題"
     }
    })
});

messages 處,若是某個控件沒有 message,將調用默認的信息ajax

required: true 值是必須的。
required: "#aa:checked" 表達式的值爲真,則須要驗證。
required: function(){} 返回爲真,表示須要驗證。json

後邊兩種經常使用於,表單中須要同時填或不填的元素。app

異步驗證

remoteURL。使用 ajax 方式進行驗證,默認會提交當前驗證的值到遠程地址,若是須要提交其餘的值,能夠使用 data 選項。遠程地址只能輸出 "true" 或 "false",不能有其餘輸出。less

rules: {
                name: {
                    required: true,
                    remote : {
                        url: "checkRoleName",           //後臺處理程序
                        type: "post",               //數據發送方式
                        dataType: "json",           //接受數據格式
                        data: {                     //要傳遞的數據
                                name: function() {
                                    return $("#name").val();
                                }
                            }
                        }
                },
                type: {
                    required: true,
                    remote : {
                        url: "checkRoleType",           //後臺處理程序
                        type: "post",               //數據發送方式
                        dataType: "json",           //接受數據格式
                        data: {                     //要傳遞的數據
                                name: function() {
                                    return $("#type").val();
                                }
                            }
                        }
                },
                permissionId:{required: true}
             },
            messages: {
                name: {required: "請填寫角色名稱",remote:"角色名稱已存在"},
                type: {required: "請填寫角色類型",remote:"角色類型已存在"},
                permissionId: {required: "請選擇權限"}
            },

 

remote: {
    url: "check-email.php",     //後臺處理程序
    type: "post",               //數據發送方式
    dataType: "json",           //接受數據格式   
    data: {                     //要傳遞的數據
        username: function() {
            return $("#username").val();
        }
    }
}

添加自定義校驗

addMethodname, method, message
自定義驗證方法
// 中文字兩個字節
jQuery.validator.addMethod("byteRangeLength", function(value, element, param) {
    var length = value.length;
    for(var i = 0; i < value.length; i++){
        if(value.charCodeAt(i) > 127){
            length++;
        }
    }
  return this.optional(element) || ( length >= param[0] && length <= param[1] );   
}, $.validator.format("請確保輸入的值在{0}-{1}個字節之間(一箇中文字算2個字節)"));

// 郵政編碼驗證   
jQuery.validator.addMethod("isZipCode", function(value, element) {   
    var tel = /^[0-9]{6}$/;
    return this.optional(element) || (tel.test(value));
}, "請正確填寫您的郵政編碼");

注意:要在 additional-methods.js 文件中添加或者在 jquery.validate.js 文件中添加。建議通常寫在 additional-methods.js 文件中。

注意:在 messages_cn.js 文件中添加:isZipCode: "只能包括中文字、英文字母、數字和下劃線"。調用前要添加對 additional-methods.js 文件的引用。

radio 和 checkbox、select 的驗證

radio 的 required 表示必須選中一個。

<input  type="radio" id="gender_male" value="m" name="gender" required />
<input  type="radio" id="gender_female" value="f" name="gender"/>

checkbox 的 required 表示必須選中。

<input type="checkbox" class="checkbox" id="agree" name="agree" required />

checkbox 的 minlength 表示必須選中的最小個數,maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" required minlength="2" />
<input type="checkbox" class="checkbox" id="spam_phone" value="phone" name="spam[]" />
<input type="checkbox" class="checkbox" id="spam_mail" value="mail" name="spam[]" />

select 的 required 表示選中的 value 不能爲空。

<select id="jungle" name="jungle" title="Please select something!" required>
    <option value=""></option>
    <option value="1">Buga</option>
    <option value="2">Baga</option>
    <option value="3">Oi</option>
</select>

select 的 minlength 表示選中的最小個數(可多選的 select),maxlength 表示最大的選中個數,rangelength:[2,3] 表示選中個數區間。

<select id="fruit" name="fruit" title="Please select at least two fruits" class="{required:true, minlength:2}" multiple="multiple">
    <option value="b">Banana</option>
    <option value="a">Apple</option>
    <option value="p">Peach</option>
    <option value="t">Turtle</option>
</select>

 例:(按鈕類型爲type="submit")

一、表單中出現hidden隱藏域時,jquery.validate就沒法驗證隱藏域,這時只要設置ignore就行

二、添加自定義驗證方法:value 是元素的值,element 是元素自己,param 是參數。

<div class="col-xs-12">
     <ul class="chooseTopic-cont" id="topicChecked">
   </ul>
     <input type="hidden" class="form-control" value = "" name="topicCount" id="topicCount" />
</div>
<script type="text/javascript">
//驗證是否選擇議題(自定義驗證)
jQuery.validator.addMethod("tCount",function(value,element,param){
              var topicList = document.getElementById("topicChecked").getElementsByTagName("li");
              if(topicList.length == 0){
                  return false;
              } 
              return true;
            },"請選擇議題");

  $(function(){
        var validator =$('#form1').validate({
        ignore : [":disabled"],//不驗證的元素(除了禁用域元素不驗證,其餘域元素都進行驗證)
              errorElement: 'p',
            errorClass: 'help_block',
            focusInvalid: true,
            debug : true,
            rules: {
                organizationCode: {required: true},
              topicCount:{tCount:true},//自定義驗證,返回true不提示,返回false則提示
                name: {
                    required: true,
                    remote : {
                        url: "checkDeptName",           //後臺處理程序
                        type: "post",               //數據發送方式
                        dataType: "json",           //接受數據格式
                        data: {                     //要傳遞的數據
                                organizationCode: function() {
                                    return $("#organizationCode").val();
                                },
                                name: function() {
                                    return $("#name").val();
                                }
                            }
                        }
                    
                    },
                parentId: {required: false},
                description: {required: false},
                sort:{required: true,number:true}
             },
            messages: {
                organizationCode: {required: "請輸入單位"},
                name : {required: "請輸入部門名稱",remote:"該單位下已存在該部門名稱"},
                parentId : {required: false},
                description : {required: false},
                sort:{required:"請輸入數字",number:"請輸入數字"}
            },
                highlight: function (e) {
                $(e).closest('.form-group').removeClass('has-info').addClass('has-error');
            },

            success: function (e) {
                $(e).closest('.form-group').removeClass('has-error');//.addClass('has-info');
                $(e).remove();
            },
            errorPlacement: function (error, element) {
                if(element.is('input[type=checkbox]') || element.is('input[type=radio]')) {
                    var controls = element.closest('div[class*="col-"]');
                    if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
                    else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
                }
                else if(element.is('.select2')) {
                    error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
                }
                else if(element.is('.chosen-select')) {
                    error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
                }
                else error.insertAfter(element.parent());
            },
             submitHandler:function(form){
                 $.ajax({
                    url: "${ctx}/organization/department/addDept?t=" + Math.random(),
                    method: "post",
                    data : $('#form1').serialize(),
                    dataType: "json",
                    beforeSend : function(){
                        $("#btn_add").attr("disabled", true);
                    },
                    success : function(data){
                        if(data.code == 1){
                            
                             window.parent.window.document.getElementById("main-frame").contentWindow.fnSearch();
                             parent.window.closeWind("conferenceDepartment_add");
                            
                        }else{
                            $("#btn_add").removeAttr("disabled");
                            parent.$.messager.alert('消息提示', data.msg, 'info');
                        }
                    }
                });
             }
         });    
  })
  </script>

 

 

 

 

參考連接:http://www.runoob.com/jquery/jquery-plugin-validate.html

相關文章
相關標籤/搜索