基于Knockout验证消息在验证函数中设置

时间:2013-07-10 22:38:45

标签: knockout.js knockout-validation

我想将消息设置为在knockout的验证函数中显示,类似于此处发生的内容:Knockout Validation Plugin Custom Error Message但没有异步。

下载了我尝试过的内容,但没有显示验证消息。

this.name = ko.observable().extend({
    validation: {
        validator: function (val) {
            return { isValid:val === 'a', message: 'the value ' + val + ' is not a' };
        },
        message: 'I dont want this default message'
    }
});

JSFiddle

有一个很好的方法吗?

1 个答案:

答案 0 :(得分:5)

close,如果规则通过,验证器应该返回true / false。我无法让message:显示该值(即使设置为具有undefined参数的函数),因此如果要将值显示回用户,则可以始终内联错误消息。

this.name = ko.observable().extend({
    validation: {
        validator: function (val) {
            if (val !== 'a') {
                this.message = 'the value ' + val + ' is not a';
                return false;
            }
            return true;
        }
    }
});

http://jsfiddle.net/gEwEX/10/