Validating several fields with the same name using jQuery Validate

前提是你 提交于 2019-12-17 17:11:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16654014/validating-several-fields-with-the-same-name-using-jquery-validate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!