33

I am using jQuery validation in my form http://jqueryvalidation.org/documentation/

I want to add the validation to all my fields but I want to ignore the hidden div's that have the class my_item.

So here is my jQuery:

 $("#myform").validate({ 
    ignore: ":hidden"
 });

How is it possible to exclude from this ignore case, the divs that have the class my_item. So something like $(":hidden").not(.my_item).

Sparky
  • 98,165
  • 25
  • 199
  • 285
novellino
  • 1,069
  • 4
  • 22
  • 51

3 Answers3

76

You can use the :not() selector:

ignore: ":hidden:not(.my_item)"
techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • thanks for that. Can I also do like :hidden:not(.item1, .item2); – novellino Nov 29 '13 at 14:10
  • however I am afraid that it does not work. Because now it does not validate my_item at all. – novellino Nov 29 '13 at 14:18
  • 4
    is this answer still valid? Any "ignore" setting I use the form is sent even if not valid. I tried ignore: [], ignore: "", ignore: ':hidden:not(#id_myimput). Always same result: I see the error notice on fields, but the form is submitted anyway. Removing any "ignore" setting fix the validation – bluantinoo Jul 28 '15 at 16:36
  • Thanks. This helped when grabbing hidden selects to validate within the materializecss framework. This was an issue since I also had some dynamically-switching/hiding content (think country -> state/province select boxes). Using this rule, I was able to at least pick up the hidden selects and then pass them to my own custom 'select checker' validation method that would first see if the select was on the stage, then proceed from there. – RomoCode Oct 14 '16 at 22:19
  • @bluantinoo It does work, but you need to do it as an option on the validate method and not in your rules object. I had issues until I looked at the docs. – Antfish Jun 19 '17 at 15:32
9

Accepted answer is perfectly fine but when you need some more control than the jQuery selector provides. You could pass a function that tests each element.

for example:

ignore: function (index, el) {
   var $el = $(el);

   if ($el.hasClass('always-validate')) {
       return false;
   }

   // Default behavior
   return $el.is(':hidden');
},
Spikolynn
  • 4,067
  • 2
  • 37
  • 44
1

In case you have no class name on your field, you can ignore it based on its name :

ignore: ['name = "field_name"']
Sébastien Gicquel
  • 4,227
  • 7
  • 54
  • 84