Roy
Roy

Reputation: 745

Looping through fields with jQuery Validation

I use the jQuery Validation plugin for my form validation needs but I'm unsure how to handle the case of looping through multiple fields of the same type when I can't determine their specific ID.

What I mean is I have a table which is filled with data using PHP. Each table row has a date field which are given an ID like: DODate[145100001], DODate[145100002], DODate[145100035] etc...

I can't know how many fields or which specific IDs each individual has so how can I use jQuery Validation to loop through and validate any and all DODate[x] fields?

Upvotes: 0

Views: 4811

Answers (2)

Sparky
Sparky

Reputation: 98738

Yes, the .addClassRules() method will create a new custom class that you can add to any input element for compound rule assignment. This is a valid approach.

HOWEVER, there is another equally valid approach to solve your issue without having to add new classes, or anything else, to your HTML markup. Use the plugin's .rules('add') method enclosed within a jQuery .each() and a "starts with" jQuery selector to target all id's starting with DODate.

$('input[id^="DODate"]').each(function() {
    $(this).rules('add', {
        required: true,  // example rule
        // another rule, etc.
    });
});

Working DEMO: http://jsfiddle.net/rW8Zd/

Also see this answer for more ways to apply rules.

Upvotes: 2

Roy
Roy

Reputation: 745

Just realised I can use a class selector and jQuery.validator.addClassRules!

Upvotes: 0

Related Questions