jquery validate 詳解二,jqueryvalidate

來源:互聯網
上載者:User

jquery validate 詳解二,jqueryvalidate
這裡只是第二篇,前面的內容請參閱上一篇
五、常用方法及注意問題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,那麼表單不會提交,只進行檢查,調試時十分方便



$().ready(function() {
 $("#signupForm").validate({
        debug:true
    });
});
如果一個頁面中有多個表單都想設定成為debug,用
$.validator.setDefaults({
   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>
<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>
</tr>
<tr>
    <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>
    </td>
</tr>

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/images/unchecked.gif") no-repeat 0px 0px;

  padding-left: 16px;

  padding-bottom: 2px;

  font-weight: bold;

  color: #EA5200;
}
label.checked {
  background:url("./demo/images/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 一起用

 

// 重設表單
$().ready(function() {
 var validator = $("#signupForm").validate({
        submitHandler:function(form){
            alert("submitted");   
            form.submit();
        }    
    });
    $("#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[]" />

 

    3.select的required表示選中的value不可為空
<select id="jungle" name="jungle" title="Please select something!" class="{required:true}">
    <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>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.