我在使用优秀的jquery
Validate Plugin
以验证某些表单。在一个表单上,我需要确保用户至少填写一组字段中的一个。我想我有一个很好的解决方案,想和大家分享。
请提出你能想到的改进建议。
我找不到做这件事的内置方法
Rebecca Murphey's custom validation method
,这很有帮助。
我从三个方面改进了这个:
-
让您传入字段组的选择器
-
指定要通过验证必须填充的组数
-
在组中的所有输入之一通过验证后立即将其显示为通过验证
验证。(见呼喊
Nick Craver
最后)
所以你可以说
“必须至少填充X个与选择器Y匹配的输入。”
最终结果是,标记如下:
<input class="productinfo" name="partnumber">
<input class="productinfo" name="description">
……是一组这样的规则:
// Both these inputs input will validate if
// at least 1 input with class 'productinfo' is filled
partnumber: {
require_from_group: [1,".productinfo"]
}
description: {
require_from_group: [1,".productinfo"]
}
第3项假设您正在添加
.checked
成功验证后返回错误消息。你可以这样做,
as demonstrated here
.
success: function(label) {
label.html(" ").addClass("checked");
}
在上面链接的演示中,我使用css为每个
span.error
X图像作为背景,除非它有类
检查
,在这种情况下,它会得到一个复选标记图像。
这是我目前的代码:
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
//Look for our selector within the parent form
var validOrNot = $(selector, element.form).filter(function() {
// Each field is kept if it has a value
return $(this).val();
// Set to true if there are enough, else to false
}).length >= numberRequired;
// The elegent part - this element needs to check the others that match the
// selector, but we don't want to set off a feedback loop where each element
// has to check each other element. It would be like:
// Element 1: "I might be valid if you're valid. Are you?"
// Element 2: "Let's see. I might be valid if YOU'RE valid. Are you?"
// Element 1: "Let's see. I might be valid if YOU'RE valid. Are you?"
// ...etc, until we get a "too much recursion" error.
//
// So instead we
// 1) Flag all matching elements as 'currently being validated'
// using jQuery's .data()
// 2) Re-run validation on each of them. Since the others are now
// flagged as being in the process, they will skip this section,
// and therefore won't turn around and validate everything else
// 3) Once that's done, we remove the 'currently being validated' flag
// from all the elements
if(!$(element).data('being_validated')) {
var fields = $(selector, element.form);
fields.data('being_validated', true);
// .valid() means "validate using all applicable rules" (which
// includes this one)
fields.valid();
fields.data('being_validated', false);
}
return validOrNot;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
万岁!
大声叫喊
现在,我的代码只是盲目地将错误消息隐藏在其他匹配字段上,而不是重新验证它们,这意味着如果出现了另一个问题(例如“只允许数字,而您输入了字母”),它将被隐藏,直到用户尝试提交为止。这是因为我不知道如何避免上述评论中提到的反馈循环。我知道一定有办法,所以
I asked a question
和
尼克克拉弗
启发了我。谢谢,尼克!
问题已解决
这本来是一个“让我分享这个,看看是否有人可以建议改进”的问题。虽然我仍然欢迎反馈,但我认为在这一点上已经很完整了。(它可以短一些,但我希望它读起来容易,不一定简洁。)所以好好享受吧!
update-now是jquery验证的一部分
这是
officially added to jQuery Validation
4/3/2012。