Dorin Grecu Dorin Grecu - 1 year ago 48
CSS Question

Method to get all declared rules from jQuery Validate?

How can I loop in JS through jQuery validation required fields? Particularly I want to add the

.required
css class to them.

EDIT:

Here is a sample code:

$("#myForm").validate({
rules: {
'firstName': "required",
'lastName': "required",
#{get 'jsValidation' /} // some rules come from outside
}
});


I just need to loop through the form fields that are marked "required" in jQuery.validate and add a css class (for example
.my_required
) to them.

Important note! not all jQuery.validate required fields have the
.required
css class.

Answer Source

There is no method as part of the jQuery Validate plugin that will return the list of declared, defined, or assigned rules back to you. The object literal contained within the .validate() method contains a list of fields and their assigned rules. A field's class and HTML5 attributes within the HTML can also contain rules that are picked up and used by the jQuery Validate plugin.

(The plugin developer probably did not see the point in creating a method just to output something you typically would have configured, therefore known, in the first place.)

"I just need to loop through the form fields that are marked "required" in jQuery.validate and add a css class"

If some fields have the required rule as per the .validate() method and other fields have the required rule as per the .required class, there is no technique for returning/selecting all fields that are "required". So if you cannot simply use a clever jQuery selector and the .addClass() method, there is no solution.

(Actually, the best solution would be to take control the HTML so that the required rule is declared consistently throughout the project... either via the .validate() method OR the HTML class attribute, not a mix of both.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download