user1338176 user1338176 - 2 months ago 6
jQuery Question

prevent form from submitting if invalid on css class

Hi I am using jQuery validate however I am trying to validate on specific css classes because of restrictions in the code, I have tried this:

$.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
});


Can anyone help.

Answer

You should know that the methods of the jQuery Validate plugin only work on the FIRST matched element when the selector contains multiple elements.

I see a lot of class selectors in your code, so I'm wondering if you're trying to target more than one element per each instance of .validate() and .rules(). If so, you also need a 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,
    });
});
Comments