jQuery验证取决于组需求

时间:2014-07-07 20:29:58

标签: javascript jquery jquery-validate depends

我有验证组的规则(需要3个中的一个)。这很好,但是,我需要只有3个要求中的1个取决于表单中的选择。

rules: {
  cloudfront_7: {
    require_from_group: {
      depends: function(element) {
        if ($( "#classify" ).val() == "PIC" ){
          return false;
        } else {
          return [1, ".verification-group"];
        }
      }
    }
  },
  cloudfront_8: {
    require_from_group: {
      depends: function(element) {
        if ($( "#classify" ).val() == "PIC" ){
          return false;
        } else {
          return [1, ".verification-group"];
        }
      }
    }
  },
  cloudfront_9: {
    require_from_group: {
      depends: function(element) {
        if ($( "#classify" ).val() == "PIC" ){
          return false;
        } else {
          return [1, ".verification-group"];
        }
      }
    }
  }
}

我注意到它只返回true而不是我写的代码,这对于require_from_group()函数是必需的。

2 个答案:

答案 0 :(得分:4)

我使用这些自定义规则解决了问题:

var verDoc_required = {
  cloudfront_7: {
    require_from_group: [1, ".verification-group"]
  },
  cloudfront_8: {
    require_from_group: [1, ".verification-group"]
  },
  cloudfront_9: {
    require_from_group: [1, ".verification-group"]
  }
}

$("#classify").change(function() {
  if ( $(this).val() == "PIC" ) {
    removeRules(verDoc_required);
  } else {
    addRules(verDoc_required);
  }
});

function addRules(rulesObj) {
  for (var item in rulesObj) {
     $('#' + item).rules('add', rulesObj[item]);
  }
}
function removeRules(rulesObj) {
  for (var item in rulesObj) {
     $('#' + item ).rules('remove');
  }
}

答案 1 :(得分:4)

你可以试试这段代码:

rules: {
cloudfront_7: {
require_from_group: {
param: [1, "..verification-group"],
depends: function(element) {return .....}
       }
    },
cloudfront_8: {
require_from_group: {
param: [1, "..verification-group"],
depends: function(element) {return .....}
       }
    },
cloudfront_9: {
require_from_group: {
param: [1, "..verification-group"],
depends: function(element) {return .....}
       }
    },
}