6

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

必须填写至少 1 个字段,但也可以同时填写两个字段。

如果它们都没有被填充,我需要 jquery validate 来抛出错误。

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

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

但是,如果只有一个字段为空,则该字段仍会获得“有效”类,因为我的有效 css 具有绿色边框,因此我不想要它(因此空字段仍会获得绿色边框)

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

4

2 回答 2

14

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

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

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

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

工作演示:http: //jsfiddle.net/NfcxX/

我的演示还显示了groups将多个错误消息合并为一个的选项。

于 2013-08-19T15:36:29.997 回答
-1
<input type="text" name="mobile" id="regMobile">
<input type="text" name="telephone" id="regTelephone">

rules: {
            mobile:{
                required: {
                    depends: function(element) {
                        return $("#regTelephone").val() == ''
                    }
                }
            },
            telephone:{
                required: {
                    depends: function(element) {
                        return $("#regMobile").val() == ''
                    }
                }
            }
}  
于 2014-01-22T12:01:02.593 回答