Max*_*kyi 5 knockout.js knockout-validation
我正在使用此处的areSame规则:
ko.validation.rules['areSame'] = {
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
validator: function (val, otherField) {
return val === this.getValue(otherField);
},
message: 'The fields must have the same value'
};
Run Code Online (Sandbox Code Playgroud)
并像这样应用它:
this.confirm = ko.observable().extend({
areSame: {
params:this.password
}
});
Run Code Online (Sandbox Code Playgroud)
但它甚至从未触发过.我把调试器放到validator规则定义的函数中:validator:function(val,otherField){debugger return val === this.getValue(otherField); 然而,流程从未访问过这一点.可能有什么不对?
编辑:
通过调用解决了不触发验证的问题ko.validation.registerExtenders();,但规则不能按预期工作.问题是otherField传递给的变量validator是对象
{params:*observable here*},getValue正如您从源代码中看到的那样,方法不期望这样.所以要么源代码错了,要么我以错误的方式为规则定义了参数.那么哪一个?
虽然它没有在Wiki中明确说明(它在示例代码中但在描述中没有)但是
你需要打电话 ko.validation.registerExtenders()
在您定义自定义规则以便注册它们之后:
ko.validation.rules['areSame'] = {
getValue: function (o) {
return (typeof o === 'function' ? o() : o);
},
validator: function (val, otherField) {
return val === this.getValue(otherField);
},
message: 'The fields must have the same value'
};
ko.validation.registerExtenders();
Run Code Online (Sandbox Code Playgroud)
为了使用您的自定义规则,您不需要"params语法",因此您只需编写:
this.confirm = ko.observable().extend({
areSame: this.password
});
Run Code Online (Sandbox Code Playgroud)
如果要使用"params语法",则需要提供自定义错误message属性,否则插件无法正确解释otherField参数:
this.confirm = ko.observable().extend({
areSame: {
params: this.password,
message: 'a custom error message'
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1799 次 |
| 最近记录: |