七、注意事項

[1]復雜的name屬性值
    當使用rules選項時,如果表單的name屬性值包含有非法的javascript標識符,必須將name值加上引號。
Js代碼

    $("#myform").validate({  
      rules: {  
        // no quoting necessary  
        name: "required",  
        // quoting necessary!  
        "user[email]": "email",  
        // dots need quoting, too!  
        "user.address.street": "required"  
      }  
    });  



[2]重構規則
    不論什么時候,當你的表單中的多個字段含有相同的驗證規則及驗證消息,重構規則可以減少很多重復。使用 addMethod 和 addClassRules 將非常有效果。  
    假使已經重構了如下規則:
Js代碼

    // alias required to cRequired with new message  
    $.validator.addMethod("cRequired", $.validator.methods.required,  
      "Customer name required");  
    // alias minlength, too  
    $.validator.addMethod("cMinlength", $.validator.methods.minlength,   
      // leverage parameter replacement for minlength, {0} gets replaced with 2  
      $.format("Customer name must have at least {0} characters"));  
    // combine them both, including the parameter for minlength  
    $.validator.addClassRules("customer", { cRequired: true, cMinlength: 2 });  


    那么使用的時候如下:
Html代碼

    <input name="customer1" class="customer" />  
    <input name="customer2" class="customer" />  
    <input name="customer3" class="customer" />  



[3]驗證消息
    當驗證了一個無效的表單元素,驗證消息顯示在用戶面前。這些消息是從哪里來的呢?有三個途徑來取得驗證消息。
        1.通過待驗證表單元素的title屬性
        2.通過默認的驗證消息
        3.通過插件設置(messages選項)
    這三種途徑的優先順序為:3 > 1 > 2
   
[4]驗證消息與Google工具欄的沖突
    有時候驗證消息會與Goole工具欄的AutoFill插件沖突。AutoFill通過替換表單元素的title屬性,以顯示提示消息。此時,驗證消息如果獲取的是title屬性值,那么就得不到我們預期想要得到的結果。當文檔載入時,可以通過如下方法避免沖突。
Js代碼

    $("input.remove_title").attr("title", "");  



[5]表單提交
    默認地,表單驗證失敗時阻止表單的提交,當驗證通過,表單提交。當然,也可以通過submitHandler來自定義提交事件。
    將提交按鈕的class屬性設置成cancel,在表單提交時可以跳過驗證。
Js代碼

    <input type="submit" name="submit" value="Submit" />  
    <input type="submit" class="cancel" name="cancel" value="Cancel" />  


    下面這段代碼將循環提交表單:
Java代碼

    $("#myform").validate({  
     submitHandler: function(form) {  
       // some other code maybe disabling submit button  
       // then:  
       $(form).submit();  
     }  
    });  


    $(form).submit() 觸發了另外一輪的驗證,驗證后又去調用submitHandler,然后就循環了??梢杂?form.submit() 來觸發原生的表單提交事件。
Java代碼

    $("#myform").validate({  
     submitHandler: function(form) {  
       form.submit();  
     }  
    }); 
jQuery相關內容: