简体   繁体   中英

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.

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,
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM