使用jQuery Validate验证具有相同名称的多个字段 [英] Validating several fields with the same name using jQuery Validate

查看:120
本文介绍了使用jQuery Validate验证具有相同名称的多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用Perl CGI处理的HTML表单,如下所示:

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>

我正在使用 jQuery验证插件对其进行验证.麻烦的是,当我调用$('#main').valid()时,它仅检查第一个字段是否为非空.如何获取所有字段的信息?

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?

推荐答案

正式文档:
jqueryvalidation.org/reference/#link-markup-recommendations

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

必选:所有需要验证的输入元素都必须具有'name'属性,否则插件将无法正常工作.'name'属性也必须是唯一的

"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" />

引用OP:

问题是,当我呼叫$('#main').valid()时,它仅检查 第一个字段为非空.如何获取所有字段的信息?

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?

它与.valid()没有特别关系,并且使用其他jQuery Validate方法也会失败.这是因为所有三个字段都具有与foo相同的name. 对于此插件,每个input 必须必须具有唯一 name.

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.

演示: jsfiddle.net/xaFZj/

DEMO: jsfiddle.net/xaFZj/

编辑:

不能使用此插件时名称重复.该演示清楚地表明,当name属性重复时,插件将失败.由于name属性是插件跟踪表单元素的方式,因此没有解决方法.

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/

jsfiddle.net/ed3vxgmy/

唯一的例外是单选或复选框组,其中每个分组中的元素将共享相同的name.

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

这篇关于使用jQuery Validate验证具有相同名称的多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆