Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/vim/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Knockout.js 未触发自定义验证规则_Knockout.js_Knockout Validation - Fatal编程技术网

Knockout.js 未触发自定义验证规则

Knockout.js 未触发自定义验证规则,knockout.js,knockout-validation,Knockout.js,Knockout Validation,我使用的是来自以下网站的arame规则: 然后像这样应用它: this.confirm = ko.observable().extend({ areSame: { params:this.password } }); 但它从未被触发过。我将调试器放入规则定义的validator函数中: 验证器:函数(val,otherField){ 调试器 return val==this.getValue(otherField); }, 然而,流从未访问过这一点。有什么不对劲吗

我使用的是来自以下网站的
arame
规则:

然后像这样应用它:

this.confirm = ko.observable().extend({
    areSame: {
       params:this.password
    }
});
但它从未被触发过。我将调试器放入规则定义的
validator
函数中: 验证器:函数(val,otherField){ 调试器 return val==this.getValue(otherField); }, 然而,流从未访问过这一点。有什么不对劲吗

编辑:

不触发验证的问题通过调用
ko.validation.registerExtenders()来解决,但该规则无法按预期工作。问题在于传递给
验证器的
otherField
变量是对象
{params:*此处可见*}
,其中作为方法的
getValue
并不期望从源代码中看到这一点。所以要么源代码错误,要么我用错误的方式为规则定义了参数。那么是哪一个呢?

虽然在中没有明确说明(它在示例代码中,但在描述中没有),但是

您需要调用
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();
为了使用自定义规则,您不需要“params语法”,只需编写:

this.confirm = ko.observable().extend({
    areSame: this.password
});
如果要使用“params syntax”,则需要提供自定义错误
消息
属性,否则插件无法正确解释
其他字段
参数:

this.confirm = ko.observable().extend({
    areSame: {
       params: this.password,
       message: 'a custom error message'
    }
});

您是否调用了
ko.validation.registerExtenders()
来注册您的自定义规则?没有,我没有这样做,因为我不知道我需要:)。请将其作为一个答案发布,就像我曾经做的那样,验证被触发了Hanks!标记为答案。这是离题的,但是你能告诉我如何使用自定义规则的本地化吗?好问题,我从来没有使用过插件的本地化功能,所以我不知道。但是编写类似于
ko.validation.localize({AreName:'Your localized error message.'})的东西在理论上应该有效。当然,您需要在您的
ko.validation.rules['AreName']
之后添加此项。谢谢您的建议,我会尝试的。请同时查看我更新的问题-验证现在已触发,但无法按预期工作
this.confirm = ko.observable().extend({
    areSame: {
       params: this.password,
       message: 'a custom error message'
    }
});