alex
alex

Reputation: 7471

Enabling validation for only a few specific hidden fields

As a corollary to this question, how would I configure jQuery Validate to validate some hidden fields in a form, but not all of them?

jQuery Validate ignores hidden fields by default, which is sort of an issue in ASP.NET projects. For instance, a page might have a form with both checkbox helpers (which generate hidden inputs), as well as custom dropdowns which may utilize many hidden inputs.

$(document).ready(function() {
    $('#myform').validate({
        ignore: [],
        // any other options and/or rules
    });
});

Using the config object like so, is there any way that I can set this up to allow me to pick and choose which specific hidden inputs to validate, without having to specify every individual input the plugin has to ignore?

Alternatively, is there a validation event hook that I could leverage in this scenario?

Upvotes: 10

Views: 6932

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241278

The default value for the ignore property is ":hidden". You could simply use the :not() pseudo class to negate a specific class from being ignored.

For instance, if you use the selector ":hidden:not(.do-not-ignore)", jQuery validate will ignore all hidden element except for hidden elements with the class .do-not-ignore:

$('#myform').validate({
    ignore: ':hidden:not(.do-not-ignore)',
    // any other options and/or rules
});

In doing so, you can add the class .do-not-ignore to your hidden elements that you still want to validate.

Upvotes: 14

Related Questions