KnockoutJS实时验证本地化

时间:2014-05-06 03:39:10

标签: knockout.js knockout-validation

我试图本地化KnockoutJS验证插件,但我需要能够即时切换语言。有一个issue open on the plugin,但它已超过2年(并且仍然开放)。

我只是尝试做的是在加载所有内容后切换验证消息的语言。这是一个例子(可以在小提琴上看到:http://jsfiddle.net/Kikketer/S6j2q/

<input data-bind='value: phone' />
<div data-bind="text: phone"></div>
<button type='button' data-bind="click: v">Validate</button>
<button type='button' data-bind='click: switchLanguage'>Switch Language</button>

使用以下JS:

ko.validation.configure({
    registerExtenders: true
});
// If I localize right away, things work
ko.validation.localize({required: '**Required'});

var InterviewTwo = function() {
    // Standard "required" validator
    this.phone = ko.observable().extend({required: true});

    // Group all of the validators
    this.errors = ko.validation.group(this);

    // Validation function
    this.v = function() {
        this.errors.showAllMessages();
    };

    // Switching languages after or before the validation
    this.switchLanguage = function() {
        // If I localize later, nothing is changed.
        ko.validation.localize({required: 'eh... sorta?'});
        ko.validation.registerExtenders();
    };
};

ko.applyBindings(new InterviewTwo());

我注意到在淘汰代码中,错误的getter方法总是返回第一个本地化错误字符串。我如何&#34;重新初始化&#34;错误字符串?

来自KnockoutJS第736行:

var errorMsgAccessor = function () {
    if (!config.messagesOnModified || isModified) {
        return isValid ? null : obsv.error; <<<< obsv.error is always the first error message
    } else {
        return null;
    }
};

1 个答案:

答案 0 :(得分:2)

您的代码会更新本地化,但新消息仅适用于下次更新。

将switchLanguage替换为:

this.switchLanguage = function() {
    // If I localize later, nothing is changed.
    ko.validation.localize({required: 'eh... sorta?'});
    for (var prop in this)
        if (ko.isObservable(this[prop]) && typeof(this[prop].valueHasMutated) === 'function')
            this[prop].valueHasMutated();        
};

<强> Fiddle