2016-10-02 77 views
-1

嗨,我使用jQuery的驗證不過我想驗證的,因爲在代碼中限制的特定CSS類,我已經試過這樣:防止形式從提交如果無效的CSS類

$.validator.setDefaults({ 
     submitHandler: function (form) { 
      alert('submitted'); 
      form.submit(); 
     } 
    }); 

    $('#shopLeft .cart').validate(); 


    $('.addon-wrap-7479-basics-0 .addon-custom').rules('add', { 
     required: true, 
     minlength: 2, 
     maxlength: 20, 
    }); 


    $('.addon-wrap-7479-description-2 .addon-custom-textarea').rules('add', { 
     required: true, 
     minlength: 2, 
     maxlength: 20, 
    }); 


    $('.addon-wrap-7479-upload-3 .addon-custom').rules('add', { 
     required: true, 
     minlength: 2, 
     maxlength: 20, 
    }); 


    $('.product-addon-nameproject .addon-custom').rules('add', { 
     required: true 
    }); 

誰能幫助。

+0

你試過的是什麼問題?你的表單的相關HTML標記在哪裏?你所展示的代碼的語法沒有任何問題,所以如果你沒有更好地解釋這些,我們無能爲力。 – Sparky

+0

我敢打賭,您的jQuery選擇器已損壞,但我們無法確定是否可以看到HTML標記。 – Sparky

回答

1

您應該知道,當選擇器包含多個元素時,jQuery Validate插件的方法僅適用於FIRST匹配元素

我在你的代碼中看到很多class選擇器,所以我想知道你是否試圖針對每個.validate().rules()的實例定位多個元素。如果是這樣,你還需要一個jQuery .each()

// more than one form with class="cart" 
$('#shopLeft .cart').each(function() { // more than one form with class="cart" 
    $(this).validate(); 
}); 


// more than one field with class="addon-custom" within a class="addon-wrap-7479-basics-0" 
$('.addon-wrap-7479-basics-0 .addon-custom').each() { 
    $(this).rules('add', { 
     required: true, 
     minlength: 2, 
     maxlength: 20, 
    }); 
});