jQuery 验证 - 需要至少一个同名输入
我正在使用 Jquery Validation 插件,并在数组中有一系列具有相同名称的输入,例如 5 个带有 name="name[]" 的输入,
我希望至少需要其中之一。有人知道该怎么做吗?谢谢!
I'm using the Jquery Validation plugin and have a series of inputs with the same name in an array, for example 5 inputs with name="name[]"
I want to have at least one of these required. Would anyone know how to do this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以更笼统地表述为“必须填充与选择器 Y 匹配的至少 X 个输入”。 (在您的情况下,X 是 1,Y 是“具有特定名称”。)
我在这里解决了一般问题:
jQuery 验证 - 要求填充一组中至少一个字段
You can state this more generally as "at least X inputs that match selector Y must be filled." (In your case, X is 1 and Y is "with a specific name.")
I addressed the general problem here:
jQuery Validate - require at least one field in a group to be filled
您可以通过 addMethod 方法根据您的需要自定义验证插件api
然后您可以创建验证表单所需的确切规则。
you can customize the validation plugin to your needs via the addMethod method from your api
then you can create the exact rule you need to validate your form.
您可以将依赖回调添加到“requires”规则中。它允许您给出一个函数来判断某个字段是否为必填字段。
除非填写了任何其他字段,否则将第一个字段设置为必填字段。
为此,将其设置为必填字段,并将依赖项回调设置为一个函数,该函数循环遍历所有其他字段,如果其中任何一个字段有值,则返回 false。请参阅: http://docs.jquery .com/Plugins/Validation/Methods/required#required.28.C2.A0dependency-callback_.29
You can add a dependency callback to your "requires" rule. It lets you give a function for whether a field is required or not.
Make the first field required unless any of the other fields are filled in.
Do this by making it required, and setting the dependency callback to a function that loops through all the other fields and returns false if any of them has a value. See: http://docs.jquery.com/Plugins/Validation/Methods/required#required.28.C2.A0dependency-callback_.29