我想创建一个自定义的剔除验证规则,该规则将采用当前可观察值的值,与其进行比较的值以及有条件的值。
我在网上看到的所有示例都只有两个参数传递到自定义验证中。
我做了一个变通办法,将带有要比较的值和条件的值传递给数组,但这有点笨拙。我的消息格式也将输出数组中的值,而不仅仅是输出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}'
}
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*/ }
}});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句