Aurelia Peters
Aurelia Peters

Reputation: 2209

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?

Upvotes: 3

Views: 7381

Answers (1)

Sparky
Sparky

Reputation: 98718

OFFICIAL DOCUMENTATION:
jqueryvalidation.org/reference/#link-markup-recommendations

"Mandated: A 'name' attribute is required for all input elements needing validation, and the plugin will not work without this. A 'name' attribute must also be unique to the form, as this is how the plugin keeps track of all input elements. However, each group of radio or checkbox elements will share the same 'name' since the value of this grouping represents a single piece of the form data."


<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.

Upvotes: 2

Related Questions