10

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?

Community
  • 1
  • 1
alex
  • 6,818
  • 9
  • 52
  • 103

1 Answers1

13

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.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
  • Im not sure this is right. hidden fields are not validated by befault. So, in saying ignore hidden fields you are basically saying validate hidden fields too. The Not says dont validate these. So you example is saying validate hidden fields except .do-not-ignore. I think you have it the wrong way round – Chillin' Aug 08 '18 at 10:34
  • @OnlineUser02094 - This is precisely what the OP wanted though. From the question: **how would I configure jQuery Validate to validate some hidden fields in a form, but not all of them?**. The answer that I provided does exactly that. It will continue to ignore hidden elements except those with a `.do-not-ignore` class. Perhaps this isn't the answer you were looking for in your particular case. – Josh Crozier Aug 08 '18 at 14:01
  • 1
    This is exactly what I was needed. – Rajesh Chaudhary Jun 02 '20 at 15:22