2016-10-02 61 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, 
    }); 
});