如何使用jQuery验证本地化 [英] How to use jquery-validate localization
问题描述
是否有一种方法可以使用存储库中现有的翻译来动态地(即从JS代码中)设置/更改错误消息的语言?
非解决方案#1 :无法加载本地化脚本(<script type="text/javascript" src="localization/messages_XX.js">
),因为无法在客户端进行更改.
非解决方案2 :使用setDefaults
设置自定义消息要求我提供自己的字符串,而不是重用现有的字符串.
使用 jQuery $.extend()
随时动态替换所有邮件.
$.extend($.validator.messages, {....});
示例:
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({ ....
演示: http://jsfiddle.net/Lwvoo39u/ >
本地化: github.com/jzaefferer/jquery-validation/tree/master/src/localization
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.
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
这篇关于如何使用jQuery验证本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!