jQuery 最后一个元素有效时验证逻辑失败

jQuery validation logic fails when last element is valid

我有一个场景,当我有 3 个下拉菜单时,需要对它们进行两次验证,但作为一个组。

1) 在 3 个下拉菜单中,有 2 个下拉菜单的值不应为 "No"。这类似于必需的验证。而不是检查空白将检查 "No".

2) 2 个下拉菜单不能有相同的值。

Fiddle

    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 不是 "No" 但仍然具有相同的值时,没有显示消息。

有人可以建议缺少什么吗?谢谢

  1. 将插件从快7年的1.7版本升级到the latest which is 1.15.

  2. require_from_group 的过时版本替换为 version 1.15 的最新版本。

  3. jQuery.format("No two fields can have same value.")替换为$.validator.format("No two...

您会发现此更新版本的工作更可预测。


编辑:

您还需要完全重写 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"
},
....

演示jsfiddle.net/nu4dcstv/