jQuery Validate插件,两个字段之一为必填项

编程入门 行业动态 更新时间:2024-10-26 18:21:34
本文介绍了jQuery Validate插件,两个字段之一为必填项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个包含2个字段的表格;手机号码.和电话号码.

I have a form with 2 fields; mobile no. and telephone no.

至少必须填写一个字段,但也可以填写两个字段.

at least 1 of the fields has to be filled in, but both can also be filled.

如果其中一个都不被填充,我需要jquery validate抛出错误.

I need jquery validate to throw an error if none of them are filled only.

我通过以下方式实现了这一目标:

I have achieved this with:

rules: { mobile:{ required: { depends: function(element) { return $("#regTelephone").val() === ''; } } }, telephone:{ required: { depends: function(element) { return $("#regMobile").val() === ''; } } } }

但是,如果只有一个字段为空,则此字段仍将获得有效"类,我不希望这样做,因为我的有效CSS具有绿色边框(因此,空白字段仍具有绿色边框)

however, if only one field is empty, this field still gets the 'valid' class, which I don't want as my valid css has a green border (so the empty field still gets a green border)

所以:我如何获取为空的字段(假设另一个字段具有值)而不获取有效的类,因此没有绿色边框?

so: how do I get the field which is empty (providing the other has a value) to not get the valid class and therefore the green border?

推荐答案

使用可选的additional-methods.js文件,有一种名为require_from_group的方法可以完全满足您的要求. (您必须至少使用插件的 版本1.11.1以避免过去的错误.)

Using the optional additional-methods.js file, there is a method called require_from_group that does exactly what you request. (You must use at least version 1.11.1 of the plugin in order to avoid a past bug.)

rules: { mobile:{ require_from_group: [1, '.mygroup'] }, telephone:{ require_from_group: [1, '.mygroup'] } }, ....

1参数是该组中需要多少个参数.在HTML标记中,组中的字段必须包含与第二个参数中指定的class匹配的class.

The 1 parameter is how many from the group are required. In the HTML markup, the fields in your group must contain a class matching the class specified in your second parameter.

<input type="text" class="mygroup" name="mobile" /> <input type="text" class="mygroup" name="telephone" />

工作演示: jsfiddle/NfcxX/

我的演示还显示了groups选项,该选项将多个错误消息组合为一个.

My demo also shows the groups option which combines the multiple error messages into one.

更多推荐

jQuery Validate插件,两个字段之一为必填项

本文发布于:2023-11-07 04:18:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565556.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   必填   插件   两个   jQuery

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!