我有3个下拉列表时有一个方案,需要对它们实现两个验证,但是作为一个组。
1)在3中,2个下拉列表应具有"否"以外的其他值。这类似于所需的验证。而不是检查空白会检查"否"。
2)否2个下拉列表可以具有相同的值。
小提琴
jQuery.validator.addMethod("require_from_group", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
var fields = $(selector, element.form);
var filled_fields = fields.filter(function() {
// it's more clear to compare with empty string
return $(this).val() != "No";
});
var empty_fields = fields.not(filled_fields);
// we will mark only first empty field as invalid
if (filled_fields.length < numberRequired){ //&& empty_fields[0] == element) {
return false;
}
return true;
// {0} below is the 0th item in the options field
}, jQuery.format("Please fill out at least {0} of these fields."));
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
var numberRequired = options[0];
var selector = options[1];
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(selector).not(element);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function(){
thisVal = $(this).val();
if(thisVal == valueToCompare){
matchesFound++;
}
});
if (matchesFound >= numberRequired){ //&& elems[0] != element) {
return false;
}
return true;
}, jQuery.format("No two fields can have same value."));
场景之一失败了,即当select1和select2不是"否"时,但仍然具有相同的值,否毫无疑问。
有人可以建议缺少什么。谢谢
-
将插件从近7年的1.7版升级到最新版本为1.15。
-
将
require_from_group
的过时版本替换为版本1.15的最新版本。 -
用
$.validator.format("No two...
替换
jQuery.format("No two fields can have same value.")
您会发现此更新版本可以预见。
编辑:
您还需要对notEqualToGroup
规则进行完整的重写:
$.validator.addMethod("notEqualToGroup", function(value, element, options) {
var isvalid = true,
values = [],
temp = [];
// put all values into an array
$(options).each(function() {
values.push($(this).val());
});
// check array for duplicates
$.each(values, function(key, val) {
if ($.inArray(val, temp) === -1) {
temp.push(val);
} else {
isvalid = false; // duplicate found
}
});
return isvalid;
}, $.validator.format("No two fields can have same value."));
本质上,将所有三个值放入数组中并检查重复项。
....
select1: {
require_from_group: [2, ".at_least_one"],
notEqualToGroup: ".at_least_one"
},
....
demo :jsfiddle.net/nu4dcstv/