I'm working on a project where the document object model is loaded from jqote templates that use input names with brackets to generate arrays on postback. The project was built this way so the rows could be sortable using jquery sortable prior to postback.
<form id="the_form">
<input type="text" id="field1" name="options[]" /><br />
<input type="text" id="field2" name="options[]" /><br />
<input type="text" id="field3" name="options[]" /><br />
<input type="submit" value="submit" />
</form>
My problem is that jquery validate does not play nice with the field names that include brackets. Sometimes it validates and sometimes it misses a field or two. I've been reading a lot of other posts stating this should work and I am wondering if I am doing something wrong or if there's a work around.
jQuery("#the_form").validate({
rules: {
"options[]": {
required: true
}
}
});
I've created a jsFiddle so others can see what I'm experiencing. If you run the jsFiddle and select Submit in the form, you'll immediately notice it only validates the first field, however if you tab through the fields, you see a different behavior. Thanks!
That is because they are currently all the same name.
They need to be different names in order to work
try this:
jQuery("#the_form").validate({
rules: {
"options": {
required: true
}
}
});
Quote:
"...My problem is that jquery validate does not play nice with the field names that include brackets."
This is true, but that's easily fixed with quotation marks. However, "brackets" are not really the problem here.
The root problem is that the plugin will not operate properly without a unique name on each field. There is no way around this.
Using a jQuery $.each()
to assign rules via the .rules('add')
method is discussed elsewhere, but it's been disproved as a viable workaround. That's because the root problem is not with selecting elements & assigning rules; the problem is that the plugin uses the name
attribute to keep track of the elements being validated. This is impossible if the name
is the same on all.