JS Live Knockout Verification Localization

I'm trying to localize the JS knockout verification plugin, but I need to be able to switch between languages ​​on the fly. In the plugin, the problem is open: https://github.com/Knockout-Contrib/Knockout-Validation/issues/158 , but it is older than 2 years (and still open).

What I'm just trying to do is switch the languages ​​of the verification messages after everything is loaded. Here is an example (can be seen on the fiddle: 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>

With the following 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());

I noticed in the knockout code, the getter method for an error always returns the first line of a localization error. How to "reinitialize" error lines?

From the KnockoutJS 736 line:

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

, .

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

+1

Source: https://habr.com/ru/post/1539375/


All Articles