jQuery Validate插件:多个中仅需一个字段 [英] jQuery Validate plugin : Only one field required out of multiple
问题描述
对此关于stackoverflow的问题 ,如果电话和移动字段为空,则会给出错误消息,但是之后填写两者中的任何一个并再次提交表格时,错误消息仍将保留.验证检查使用输入的旧值进行,刷新页面后,它将使用新值.如果有人可以帮助我解决此问题,我将不胜感激
Wrt this question on stackoverflow , if the telephone and mobile fields are empty then it gives an error message but after that when either of the two is filled and the form is submittted again then too the error message remains . The validation check takes place with the old value of the input and when the page is refreshed then it takes new values. I will be grateful if anyone can help me fixing this problem ??
推荐答案
1)按照此jsFiddle 使用 depends
选项,仍然会遇到很多问题.这些规则似乎根本不起作用,因为总是需要两个字段.
1) As per the question you've linked, I constructed this jsFiddle using the depends
option and still see lots of issues. The rules do not seem to work at all, where both fields are always required.
2)additional-methods.js
文件中包含一个require_from_group
规则.对于要定位的规则,两个字段必须具有相同的class
,在这种情况下为.group
.但是此方法有一些已知的错误,它会禁用所有其他规则表格
2) There is a require_from_group
rule included in the additional-methods.js
file. The two fields must have the same class
for the rule to target, in this case, .group
. But this method has some known bugs where it disables all of the other rules on the form
演示: http://jsfiddle.net/SvSrR/
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
groups: {
name: "telephone mobile"
},
rules: {
telephone: {
require_from_group: [1, '.group']
},
mobile: {
require_from_group: [1, '.group']
}
}
});
});
3)相反,我构造了一个名为customrule
的自定义规则(您可以根据需要命名),并且该规则可以正常运行.我还使用groups
选项将两个错误消息合并为一个.
3) Instead, I constructed a custom rule called customrule
(you can name it however you want) and it's working as I believe it should. I also used the groups
option to combine the two error messages into one.
工作示例: http://jsfiddle.net/2g8hL/
Working DEMO: http://jsfiddle.net/2g8hL/
$(document).ready(function () {
$.validator.addMethod("customrule", function (value, element) {
return (!($("#mobile").val() === '') || !($("#telephone").val() === ''));
}, "please fill out at least one");
$('#myform').validate({ // initialize the plugin
groups: {
name: "telephone mobile"
},
rules: {
telephone: {
customrule: true
},
mobile: {
customrule: true
}
}
});
});
这篇关于jQuery Validate插件:多个中仅需一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!