如何更改 JQuery 验证器语言消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6181886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:30:55  来源:igfitidea点击:

How to Change JQuery Validator Language Message

jqueryjquery-validate

提问by Luis Alvarado

Am using the JQuery Validator from http://bassistance.de/jquery-plugins/jquery-plugin-validation/. How can i make it so that the messages are custom and not in english.

我正在使用来自http://bassistance.de/jquery-plugins/jquery-plugin-validation/的 JQuery 验证器。我怎样才能使消息是自定义的而不是英文的。

采纳答案by Dave Sag

Do it like this:

像这样做:

$(document).ready(function() {
  $("form#login").validate({
    lang: 'en'  // or whatever language option you have.
  });
});

If the language you wish to supply is not one of the default languages, then do this:

如果您希望提供的语言不是默认语言之一,请执行以下操作:

$.tools.validator.localize("fi", {
    '*'          : 'Virheellinen arvo',
    ':email'     : 'Virheellinen sähköpostiosoite',
    ':number'    : 'Arvon on oltava numeerinen',
    ':url'       : 'Virheellinen URL',
    '[max]'      : 'Arvon on oltava pienempi, kuin ',
    '[min]'      : 'Arvon on oltava suurempi, kuin ',
    '[required]' : 'Kentän arvo on annettava'
});

  $("form#login").validate({
    lang: 'fi'
  });

See these instructionsfor more.

有关更多信息,请参阅这些说明

回答by andre_lost

If you look into the directory "localization", you could find different .js files that cointains error messages in different languages. [something like "messages_XX.js"]

如果您查看“本地化”目录,您会发现不同的 .js 文件包含不同语言的错误消息。[类似于“messages_XX.js”]

Choose the file of the language you need and just add the following line, into the tag , after the inclusion of the jquery.validate.js

选择您需要的语言的文件,并在包含 jquery.validate.js 后将以下行添加到标记中

<script type="text/javascript" src="localization/messages_XX.js"></script>

回答by astroanu

The best method is to extend the plugin like this when needed

最好的方法是在需要时像这样扩展插件

$.extend($.validator.messages, {
    required: "my required message",
    ....
});

回答by isaac weathers

Here would be your JSON structure in your initial validation script like Alex has:

这将是您的初始验证脚本中的 JSON 结构,就像Alex一样:

   rules: {
        accntTypeCL: {
            required: true,
        },
        accntNoCL: {
            required: true,
            minlength: 19,
            numberDash: true,
        }
    },                      
    messages : {
        accntTypeCL : {
            required : Messages.ERR_TEST,
        },
        accntNoCL : {
            required : Messages.ERR_TEST,
            numberDash : Messages.ERR_TEST,
            minlength : Messages.ERR_TEST2,
        },
    }

//This would be in your messages.js file... But you'll need to make sure you are using a Java backend or something that will pull the messages.js correctly
//For IBM worklight this worked great       

    Messages = {
// Add here your messages for the default language. 
// Generate a similar file with a language suffix containing the translated messages

ERR_TOPLEVEL : '<span role=\"presentation\">One or more of the required fields was left blank or is invalid.<\/span>',
//Test Messages for tracing
ERR_TEST: 'This be the test yar!',
ERR_TEST2: 'This be the test2 yar!'
};

This way you can re-use the same functions, the same additional methods, and the same error types and just use the correct messages.js file based on the language of the html that should be detected in the browser or however you have it. This particular method worked good for me.

通过这种方式,您可以重用相同的功能、相同的附加方法和相同的错误类型,并且只使用基于应该在浏览器中检测到的 html 语言的正确的 messages.js 文件,或者您拥有它。这种特殊的方法对我很有用。

回答by olefrank

You could also put the error messages directly in the markup like this:

您还可以将错误消息直接放在标记中,如下所示:

<input required data-msg="Please fill this field">
<input data-rule-minlength="2" data-rule-maxlength="4" data-msg-minlength="At least two chars" data-msg-maxlength="At most fours chars">

See documentation

查看文档

If you use some kind of localization plugin, you can move the messages out in separate files. Here I use i18n-2 (npm module):

如果您使用某种本地化插件,您可以将消息移出单独的文件。这里我使用 i18n-2(npm 模块):

<input id="email" type="email" name="email" data-msg=__("pages.apply.form.email.errormsg.required"))

Then I put my language files in a folder:

然后我将我的语言文件放在一个文件夹中:

/locales
    da.json
    en.json

en.json

en.json

"pages": {
        "apply": {
            "subtitle": "Apply here",
            "form": {
                    "email": {
                        "title": "Email",
                        "placeholder": "Your email address",
                        "warning": "NB! DER AFSENDES EN MAIL HERTIL",
                        "errormsg": {
                            "required": "Enter a valid email address"
                        }
                    }
             }
        }
 }

回答by Basheer AL-MOMANI

Take look at my solution

看看我的解决方案

jQuery.extend(jQuery.validator.messages, {
        required: abp.localization.localize("FormValidationMessageRequired"),//"This field is required.",
        remote: "Please fix this field.",
        email: abp.localization.localize("FormValidationMessageEmail"),//"Please enter a valid email address.",
        url: abp.localization.localize("FormValidationMessageUrl"),//"Please enter a valid URL.",
        date: abp.localization.localize("FormValidationMessageDate"),//"Please enter a valid date.",
        dateISO: "Please enter a valid date (ISO).",
        number:  abp.localization.localize("FormValidationMessageNumber"),//"Please enter a valid number.",
        digits: "Please enter only digits.",
        creditcard: "Please enter a valid credit card number.",
        equalTo:  abp.localization.localize("FormValidationMessageDataEquals"),//"Please enter the same value again.",
        accept: "Please enter a value with a valid extension.",
        maxlength: jQuery.validator.format("Please enter no more than {0} characters."),
        minlength: jQuery.validator.format(abp.localization.localize("FormValidationMessageMinlength")),//jQuery.validator.format("Please enter at least {0} characters."),
        rangelength: jQuery.validator.format("Please enter a value between {0} and {1} characters long."),
        range: jQuery.validator.format("Please enter a value between {0} and {1}."),
        max: jQuery.validator.format(abp.localization.localize("FormValidationMessageMax")),//jQuery.validator.format("Please enter a value less than or equal to {0}."),
        min: jQuery.validator.format(abp.localization.localize("FormValidationMessageMin"))//jQuery.validator.format("Please enter a value greater than or equal to {0}.")
    });

and this func abp.localization.localize(Key)return the localized string based on the current culture, this function is from the framework that I used called aspnetboilerplate

这个函数abp.localization.localize(Key)返回基于当前文化的本地化字符串,这个函数来自我使用的框架,称为aspnetboilerplate

for more info see this stack overflow thread jQuery validation: change default error message

有关更多信息,请参阅此堆栈溢出线程jQuery 验证:更改默认错误消息

回答by Vincent Decaux

If you use npm/ yarnto manage your assets, you can simply import the localization file like this (replace iso code of course, here it's french):

如果您使用npm/yarn来管理您的资产,您可以简单地像这样导入本地化文件(当然要替换 iso 代码,这里是法语)

import 'jquery-validation';
import 'jquery-validation/dist/localization/messages_fr';

Then use :

然后使用:

$form.validate({
    lang: 'fr',
});

回答by alex

Use the messagesobject.

使用messages对象。

Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback. The callback is called in the scope of the validator and with the rule's parameters as the first and the element as the second arugment, it must return a String to display as the message.

定义自定义消息的键/值对。键是元素的名称,值是要为该元素显示的消息。可以使用带有每个规则的特定消息的另一个映射来代替普通消息。覆盖元素的标题属性或方法的默认消息(按该顺序)。每条消息都可以是字符串或回调。回调在验证器的范围内被调用,规则的参数作为第一个参数,元素作为第二个参数,它必须返回一个字符串以显示为消息。

Example

例子

$(".selector").validate({
   rules: {
     name: "required",
     email: {
       required: true,
       email: true
     }
   },
   messages: {
     name: "Please specify your name",
     email: {
       required: "We need your email address to contact you",
       email: "Your email address must be in the format of [email protected]"
     }
   }
})

Source.

来源

回答by Vinod Raut

For the PHP i have done it like this.

对于 PHP,我已经这样做了。

$.validator.messages = $.extend({}, $.validator.messages, {
        required: '<?= __("This field is required.") ?>',
        remote: '<?= __("Please fix this field.") ?>',
        email: '<?= __("Please enter a valid email address.") ?>',
        url: '<?= __("Please enter a valid URL.") ?>',
        date: '<?= __("Please enter a valid date.") ?>',
        dateISO: '<?= __("Please enter a valid date (ISO).") ?>',
        number: '<?= __("Please enter a valid number.") ?>',
        digits: '<?= __("Please enter only digits.") ?>',
        equalTo: '<?= __("Please enter the same value again.") ?>',
        maxlength: $.validator.format( '<?= __("Please enter no more than {0} characters.") ?>' ),
        minlength: $.validator.format( '<?= __("Please enter at least {0} characters.") ?>' ),
        rangelength: $.validator.format( '<?= __("Please enter a value between {0} and {1} characters long.") ?>' ),
        range: $.validator.format( '<?= __("Please enter a value between {0} and {1}.") ?>' ),
        max: $.validator.format( '<?= __("Please enter a value less than or equal to {0}.") ?>' ),
        min: $.validator.format( '<?= __("Please enter a value greater than or equal to {0}.") ?>' ),
        step: $.validator.format( '<?= __("Please enter a multiple of {0}.") ?>' )
    })

So the languages changes as per the gettext these error messages also get change.

因此,语言根据 gettext 发生变化,这些错误消息也会发生变化。

回答by Jordan Wallwork

just enter a "required" value in the json that defines the validation. check the demos source, but its in the messages category

只需在定义验证的 json 中输入一个“必需”值。检查演示源,但它在消息类别中