天天看點

jquery validate 詳解二

五、常用方法及注意問題

1.用其他方式替代預設的SUBMIT

$().ready(function() {

 $("#signupForm").validate({

        submitHandler:function(form){

            alert("submitted");   

            form.submit();

        }    

    });

});

可以設定validate的預設值,寫法如下:

$.validator.setDefaults({

 submitHandler: function(form) { alert("submitted!");form.submit(); }

如果想送出表單, 需要使用form.submit()而不要使用$(form).submit()

2.debug,隻驗證不送出表單

如果這個參數為true,那麼表單不會送出,隻進行檢查,調試時十分友善

        debug:true

如果一個頁面中有多個表單都想設定成為debug,用

   debug: true

})

3.ignore:忽略某些元素不驗證

ignore: ".ignore"

4.更改錯誤資訊顯示的位置

errorPlacement:Callback 

 Default: 把錯誤資訊放在驗證的元素後面 

指明錯誤放置的位置,預設情況是:error.appendTo(element.parent());即把錯誤資訊放在驗證的元素後面

errorPlacement: function(error, element) {  

    error.appendTo(element.parent());  

}

//示例:

<tr>

    <td class="label"><label id="lfirstname" for="firstname">First Name</label></td>

    <td class="field"><input id="firstname" name="firstname" type="text" value="" maxlength="100" /></td>

    <td class="status"></td>

</tr>

    <td style="padding-right: 5px;">

        <input id="dateformat_eu" name="dateformat" type="radio" value="0" />

        <label id="ldateformat_eu" for="dateformat_eu">14/02/07</label>

    </td>

    <td style="padding-left: 5px;">

        <input id="dateformat_am" name="dateformat" type="radio" value="1"  />

        <label id="ldateformat_am" for="dateformat_am">02/14/07</label>

    <td></td>

    <td class="label">&nbsp;</td>

    <td class="field" colspan="2">

        <div id="termswrap">

            <input id="terms" type="checkbox" name="terms" />

            <label id="lterms" for="terms">I have read and accept the Terms of Use.</label>

        </div>

errorPlacement: function(error, element) {

    if ( element.is(":radio") )

        error.appendTo( element.parent().next().next() );

    else if ( element.is(":checkbox") )

        error.appendTo ( element.next() );

    else

        error.appendTo( element.parent().next() );

代碼的作用是:一般情況下把錯誤資訊顯示在<td class="status"></td>中,如果是radio顯示在<td></td>中,如果是 checkbox顯示在内容的後面

errorClass:String  Default: "error" 

指定錯誤提示的css類名,可以自定義錯誤提示的樣式

errorElement:String  Default: "label" 

用什麼标簽标記錯誤,預設的是label你可以改成em

errorContainer:Selector 

顯示或者隐藏驗證資訊,可以自動實作有錯誤資訊出現時把容器屬性變為顯示,無錯誤時隐藏,用處不大

errorContainer: "#messageBox1, #messageBox2"

errorLabelContainer:Selector

把錯誤資訊統一放在一個容器裡面。

wrapper:String

用什麼标簽再把上邊的errorELement包起來

一般這三個屬性同時使用,實作在一個容器内顯示所有錯誤提示的功能,并且沒有資訊時自動隐藏

errorContainer: "div.error",

errorLabelContainer: $("#signupForm div.error"),

wrapper: "li"

5更改錯誤資訊顯示的樣式

設定錯誤提示的樣式,可以增加圖示顯示,在該系統中已經建立了一個validation.css專門用于維護校驗檔案的樣式

input.error { border: 1px solid red; }

label.error {

  background:url("./demo/p_w_picpaths/unchecked.gif") no-repeat 0px 0px;

  padding-left: 16px;

  padding-bottom: 2px;

  font-weight: bold;

  color: #EA5200;

label.checked {

  background:url("./demo/p_w_picpaths/checked.gif") no-repeat 0px 0px;

6每個字段驗證通過執行函數

success:String,Callback

要驗證的元素通過驗證後的動作,如果跟一個字元串,會當做一個css類,也可跟一個函數

success: function(label) {

    // set &nbsp; as text for IE

    label.html("&nbsp;").addClass("checked");

    //label.addClass("valid").text("Ok!")

添加"valid" 到驗證元素, 在CSS中定義的樣式<style>label.valid {}</style>

success: "valid"

7驗證的觸發方式修改

下面的雖然是boolean型的,但建議除非要改為false,否則别亂添加。

onsubmit:Boolean  Default: true 

送出時驗證. 設定唯false就用其他方法去驗證

onfocusout:Boolean  Default: true 

失去焦點是驗證(不包括checkboxes/radio buttons)

onkeyup:Boolean  Default: true 

在keyup時驗證.

onclick:Boolean  Default: true 

在checkboxes 和 radio 點選時驗證

focusInvalid:Boolean  Default: true 

送出表單後,未通過驗證的表單(第一個或送出之前獲得焦點的未通過驗證的表單)會獲得焦點

focusCleanup:Boolean  Default: false 

如果是true那麼當未通過驗證的元素獲得焦點時,移除錯誤提示。避免和 focusInvalid 一起用

// 重置表單

 var validator = $("#signupForm").validate({

    $("#reset").click(function() {

        validator.resetForm();

8異步驗證

remote:URL

使用ajax方式進行驗證,預設會送出目前驗證的值到遠端位址,如果需要送出其他的值,可以使用data選項

remote: "check-email.php"

remote: {

    url: "check-email.php",     //背景處理程式

    type: "post",               //資料發送方式

    dataType: "json",           //接受資料格式   

    data: {                     //要傳遞的資料

        username: function() {

            return $("#username").val();

        }

    }

遠端位址隻能輸出 "true" 或 "false",不能有其它輸出

9添加自定義校驗

addMethod:name, 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));

}, "請正确填寫您的郵政編碼");

10radio和checkbox、select的驗證

1.radio的required表示必須選中一個

<input  type="radio" id="gender_male" value="m" name="gender" class="{required:true}" />

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

2.checkbox的required表示必須選中

<input type="checkbox" class="checkbox" id="agree" name="agree" class="{required:true}" />

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

<input type="checkbox" class="checkbox" id="spam_email" value="email" name="spam[]" class="{required:true, 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[]" />