Reputation: 2877
I managed to validate multiple form fields with identical names, such as first_name[]
, using jQuery Validate plugin and this workaround (quoted here).
However error messages are displayed only for the first instance of a field, not the next ones.
Why is that?
For the record, the solution presented in the links above consists in editing jquery.validate.js and change the checkForm function content into:
checkForm: function() {
this.prepareForm();
for ( var i = 0, elements = (this.currentElements = this.elements()); elements[i]; i++ ) {
if (this.findByName( elements[i].name ).length != undefined && this.findByName( elements[i].name ).length > 1) {
for (var cnt = 0; cnt < this.findByName( elements[i].name ).length; cnt++) {
this.check( this.findByName( elements[i].name )[cnt] );
}
} else {
this.check( elements[i] );
}
}
return this.valid();
}
Then using this kind of parameters when calling the plugin:
rules: {
"field_name[]": "required"
}
Upvotes: 0
Views: 1167
Reputation: 98718
Quote OP:
"I managed to validate multiple form fields with identical names, such as
first_name[]
, using jQuery Validate plugin and this workaround (quoted here)."
I strongly recommend against editing the source code of any plugin.
You have to make sure you never over-write it when updating.
You create confusion for the next person that works on the project.
You may introduce any number of unknown bugs.
This is a very popular and thoroughly tested plugin. Edit the source and forget about all of that... you might as well write your own plugin.
Besides, the hack you're quoting is more than three years old... how do you know that it's still supposed to work (if it ever did work) properly on the latest version of the plugin?
Quote OP:
"However error messages are displayed only for the first instance of a field, not the next ones.
Why is that?"
That's exactly what happens with this plugin when you have multiple fields sharing the same name
... only the first instance is recognized. There is no workaround for this.
The plugin was designed to keep track of the form inputs via their name
attributes. I don't know how any hack is going to get around that, since you still need to keep track of everything without duplication.
However, you should not need to do any of this at all. The plugin is designed to handle field name
's that are part of an array... "field[1]"
, "field[2]"
, etc. are acceptable.
If your form is static, simply create unique field names.
If your form is dynamic, use an incremental counter to properly create an array index so that every field ends up with a unique name
.
Upvotes: 1