1

Is there a way to dynamically (i.e. from JS code) set/change the language of error messages, using the existing translations available in the repo?

Non-solution #1: Loading a localization script (<script type="text/javascript" src="localization/messages_XX.js">) won't work because it cannot be changed on the client-side.

Non-solution #2: Setting custom messages with setDefaults requires me to come up with my own strings instead of reusing the existing ones.

1 Answer 1

2

Use jQuery $.extend() to dynamically replace all messages at any time.

$.extend($.validator.messages, {....});

Example:

var en = {
        required: "This field is required.",
        ....
    },
    ca = {
        required: "Aquest camp és obligatori.",
        ....
    },
    de = {
        required: "Dieses Feld ist ein Pflichtfeld.",
        ....
    };

$('#language').on('change', function() {
    $.extend($.validator.messages, eval($(this).val()));
});

$('#myform').validate({ ....

DEMO: http://jsfiddle.net/Lwvoo39u/

Localization: github.com/jzaefferer/jquery-validation/tree/master/src/localization

Sign up to request clarification or add additional context in comments.

2 Comments

I marked this answer as accepted even though it's not exactly what I was looking for. To clearify: I'd like to use the localization files from the repo as-is (directly benefiting from future changes/improvements to those files); with your solution (or the similar 'setDefaults' solution), I have to manually copy the localization data from messages_de.js, messages_et.js etc. into my own code, requiring me to manually manage that data. I was hoping for a dynamic mechanism similar to e.g. Datatables (datatables.net) which provides an API to dynamically load the lib's own localization data.
@dr_barto, there is practically nothing contained in the localizations that should change over time, so once the messages are copied into your own file, there is no code to "maintain".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.