自定义Knockout验证3参数

时间:2014-07-11 11:44:50

标签: knockout.js knockout-validation

我想创建一个自定义的淘汰赛验证规则,该规则会接受当前可观察的值,与之比较的值以及条件。

我在网上看到的所有示例都只有两个参数传递到自定义验证中。

我已经做了一个解决方法来传递一个数组,其值为compare和条件,但这有点笨重。我的消息格式也输出数组中的值,而不仅仅是otherVal

例如:

/*
* Compares two values only if the specified condition is true.
* Parameters: 
*   array[0] - otherVal
*   array[1] - conditional
*
* Returns:
*   true if the condition is false.
*   true if the condition is true AND val is lessThanOrEqualTo otherVal
*   false otherwise
*
* Usage:
*   Used to validate observables conditionally.
*
* Example:
*   self.salary = ko.observable().extend({ 
                      mustLessThanOrEqualConditional: [100, isFieldEditable]})
*/
ko.validation.rules['mustLessThanOrEqualConditional'] = {
  validator: function(val, array) {
      if (array[1]) {
          return val <= array[0];
      }
      return true;
  },
  message: 'The field must be <= {0}'
};

有没有办法将三个参数传递给验证函数,例如:

ko.validation.rules['mustLessThanOrEqualConditional'] = {
    validator: function(val, otherVal, condition) {
        if(condition){
            return val <= otherVal;
        }
        return true;
    },
    message: 'The field must be <= {0}'
}

1 个答案:

答案 0 :(得分:7)

您可以使用对象代替Array

ko.validation.rules['mustLessThanOrEqualConditional'] = {
  validator: function(val, params) {
      if (params.condition) {
          return val <= params.otherVal;
      }
      return true;
  },
  message: 'The field must be <= {0}'
};

model.obs.extend({ mustLessThanOrEqualConditional: {
                       params: { otherVal: 3, condition: 1 != 0 }
                   }
                });

虽然在您的情况下,我建议改为使用onlyIf功能:

ko.validation.rules['mustLessThanOrEqualConditional'] = {
  validator: function(val, params) {
      return val <= params.otherVal;
  },
  message: 'The field must be <= {0}'
};

model.obs.extend({ mustLessThanOrEqualConditional: {
                       onlyIf: function () { /* your test here */ },
                       params: { otherVal: 3 }
                   }
                });

由于我是一个非常善良的人,这是我使用的规则:

ko.validation.rules['compareTo'] = {
    message: "Compare to",
    validator: function (val, params) {
        if (val === null || params.value() === null)
            return params.allowNull;
        switch (params.way) {
            case "<": return val < params.value();
            case "<=": return val <= params.value();
            case ">": return val > params.value();
            case ">=": return val >= params.value();
            default: throw new Error("params is not well defined");
        }
    }
}

model.obs.extend({ compareTo: { 
                       message:"your message", 
                       params: { 
                                   way: ">=", 
                                   value: model.otherObs, 
                                   allowNull: true 
                       }, 
                       onlyIf: function () { /*your test*/ } 
                    }});