Kit Peters Kit Peters - 3 months ago 8
jQuery Question

Validating several fields with the same name using jQuery Validate

I have an HTML form that I'm processing with Perl CGI, like so:

<form action="process.cgi" id="main">
<input type="text" name="foo" class="required" />
<input type="text" name="foo" class="required" />
<input type="text" name="foo" class="required" />
</form>


And I'm validating it with the jQuery Validation plugin. Trouble is, when I call
$('#main').valid()
, it only checks that the first field is non-empty. How to I get it to check all the fields?

Answer
<input type="text" name="foo" class="required" />
<input type="text" name="foo" class="required" />
<input type="text" name="foo" class="required" />

Quote OP:

Trouble is, when I call $('#main').valid(), it only checks that the first field is non-empty. How to I get it to check all the fields?

It has nothing specifically to do with .valid() and it will fail the same using other jQuery Validate methods. That's because all three fields have the same name of foo. For this plugin each input must have a unique name.

DEMO: jsfiddle.net/xaFZj/


EDIT:

You cannot have duplicate names while using this plugin. This demo clearly shows that the plugin will fail when the name attribute is duplicated. There is no workaround since the name attribute is how the plugin keeps track of the form elements.

jsfiddle.net/ed3vxgmy/

The only exception is a radio or checkbox group where the elements in each grouping will share the same name.