问题
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:
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
来源:https://stackoverflow.com/questions/37594585/how-to-use-jquery-validate-localization