Ignore all hidden div but not one in jQuery validation
Asked Answered
A

3

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).

Anagrammatize answered 29/11, 2013 at 14:6 Comment(0)
K
76

You can use the :not() selector:

ignore: ":hidden:not(.my_item)"
Kuo answered 29/11, 2013 at 14:8 Comment(5)
thanks for that. Can I also do like :hidden:not(.item1, .item2);Anagrammatize
however I am afraid that it does not work. Because now it does not validate my_item at all.Anagrammatize
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 validationRodriguez
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.Corrientes
@Rodriguez 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.Altdorf
I
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');
},
Intellection answered 4/12, 2017 at 12:47 Comment(2)
This is perfect, Thank youCydnus
Exactly what I was looking for. <3Calicle
I
1

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

ignore: ['name = "field_name"']
Imbecility answered 22/1, 2021 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.