Custom Knockout Validation 3 Parameters

有些话、适合烂在心里 提交于 2019-12-04 13:07:13

Instead of an Array, you can use an object:

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 }
                   }
                });

Although in your case, I would suggest using the onlyIf functionnality instead:

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 }
                   }
                });

As I am a very nice person, here is the rule I use:

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*/ } 
                    }});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!