How to use jquery-validate localization

社会主义新天地 提交于 2021-02-04 16:46:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!