jQuery 仅当第一个为真时才验证第二个方法

jQuery validate fire second method only if first was true

我遇到了一个具体问题。我正在使用 jQuery 验证,并希望在一个字段上设置多个自定义规则,代码如下所示

var validate = {
  opt: {
    onkeyup: function(element, event) {
      if (event.which === 9 && this.elementValue(element) === "") {
        return;
      } else {
        validator.element(element);
      }
    },

    rules: {
      'user[password]': {
        method1: {},
        method2: {},
        required: true,
      },
    },
  },
  messages: {}
};

jQuery.validator.addMethod('method1', function(a, b, c) {
  return false;
});
jQuery.validator.addMethod('method2', function(a, b, c) {
  console.log('test');
  return true;
});

问题是方法 2 只有在方法 1 返回 true 时才会触发。代码就是一个例子。是否有任何选项可以设置这样的行为。我错过了什么吗?我在其他页面上得到了类似的代码并且它工作正常。

The problem is the method 2 fires only if method 1 is returning true. Code is an example.

规则按字段计算,一次一个 (按照声明的顺序,required除外)

如果该字段是 required,则 required 消息将显示,直到在该字段中键入内容。一旦该字段开始填写,其余方法将按顺序触发... method1 消息将显示,直到满足该规则 (returns true)。那么 method2 只会在满足 requiredmethod1 (true) 后触发。

因为你的method1总是false,永远不会满足,method2永远不会被评估。

Is there any option that's setting behaviour like this.

不行,就是这么设计的,而且没有关闭的选项。否则,您会在一个字段上同时显示多条消息。

Am I missing something?

如果您需要同时触发两个自定义方法,则应将这两个规则合并为一个方法。

I got [have] similar code on other page and it works correctly.

取决于您对 "similar" 和 "correctly" 的定义。如果您认为同时评估两个规则,那是不可能的。上面 OP 中的代码 正在按预期和设计工作。