Localizing Knockout-Validation
How to localize validation messages using Knockout-Validation localization files.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<script src="https://cdn.rawgit.com/Knockout-Contrib/Knockout-Validation/master/dist/knockout.validation.js"></script>
<div id="content">
<select data-bind="options: locales, value: currentLocale, optionsCaption: 'ca-ES'"></select>
<input type="text" data-bind="textInput: value" />
</div>
CSS
select, input {
padding: 4px 6px;
}
input {
margin-right: 5px;
}
.validationMessage {
color: #b94a48;
}
input.validationElement {
border: 1px solid #b94a48;
}
JavaScript
// These are all the locales available in Knockout-Validation
var locales = ["bg-BG", "ca-ES", "cs-CZ", "da-DK", "de-DE", "el-GR", "es-ES", "fa-IR", "fr-FR", "he-IL", "hr-HR", "hu-HU", "it-IT", "ja-JP", "ko-KR", "lv-LV", "nb-NO", "nl-BE", "nl-NL", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sv-SE", "tr-TR", "zh-CN"];
ko.validation.init({
messagesOnModified: false,
decorateInputElement: true,
decorateElementOnModified: false
}, true);
var viewModel = {
value: ko.observable().extend({required: true}),
locales: ko.observableArray(locales),
currentLocale: ko.observable()
};
// Subscribe to changes of currentLocale observable and apply the new locale
viewModel.currentLocale.subscribe(function (newValue) {
newValue || (newValue = 'en-us');
console.log('Changing locale to', newValue);
// Apply localization
ko.validation.locale(newValue);
// This is needed to force the rule's message to update
viewModel.value.valueHasMutated();
});
ko.applyBindings(viewModel);
//-------------------------------------------------------------------------------------------------------
// Helper to generate script tags to load localization files
(function injectLocalization() {
var baseUrl = 'https://cdn.rawgit.com/Knockout-Contrib/Knockout-Validation/master/localization/',
head = document.getElementsByTagName('head')[0];
locales.forEach(function (name) {
var script = document.createElement('script');
script.src = baseUrl + name + '.js';
head.appendChild(script);
});
})();