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.
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. However, the object literal contained within the .validate()
method contains a list of fields and their assigned rules.
console.log($("#myForm").validate().settings.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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With