如何更改JQuery Validator语言消息

时间:2011-05-31 00:40:00

标签: jquery jquery-validate

使用http://bassistance.de/jquery-plugins/jquery-plugin-validation/中的JQuery Validator。我怎样才能使消息是自定义的而不是英文的。

13 个答案:

答案 0 :(得分:32)

如果您查看目录“本地化”,您可以找到不同的.js文件,这些文件包含不同语言的错误消息。 [类似“messages_XX.js”]

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

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

答案 1 :(得分:17)

这样做:

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

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

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

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

有关详情,请参阅these instructions

答案 2 :(得分:6)

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

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

答案 3 :(得分:5)

这是您的初始验证脚本中的JSON结构,如Alex has

   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!'
};

通过这种方式,您可以重复使用相同的函数,相同的附加方法和相同的错误类型,并根据应在浏览器中检测到的html语言使用正确的messages.js文件,或者您有它。这种特殊方法对我有用。

答案 4 :(得分:3)

看看我的解决方案

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}.")
    });

并且此func abp.localization.localize(Key)根据当前文化返回本地化字符串,此函数来自我使用的名为aspnetboilerplate的框架

有关详细信息,请参阅此堆栈溢出线程jQuery validation: change default error message

答案 5 :(得分:2)

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

<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">

请参阅documentation

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

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

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

/locales
    da.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"
                        }
                    }
             }
        }
 }

答案 6 :(得分:1)

使用messages对象。

  

定义自定义的键/值对   消息。 Key是一个名字   element,重视要显示的消息   对于那个元素。而不是平原   留言具体的另一张地图   可以使用每个规则的消息。   覆盖一个的title属性   元素或默认消息   方法(按此顺序)。每条消息   可以是String或Callback。该   回调是在范围内调用的   验证者和规则的   参数作为第一个和   它作为第二个安慰因素   必须返回一个String才能显示为   消息。

实施例

$(".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 name@domain.com"
     }
   }
})

Source

答案 7 :(得分:1)

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

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

然后使用:

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

答案 8 :(得分:1)

对于PHP,我是这样做的。


  hub:
    image: selenium/hub:3.14.0-gallium
    ports:
      - "4444:4444"

  chrome:
    image: selenium/node-chrome:3.14.0-gallium
    volumes:
      - /dev/shm:/dev/shm
      - local_chrome_data_download:/tmp/downloads
    depends_on:
      - hub
    environment:
      HUB_HOST: hub

因此,语言会根据gettext更改,这些错误消息也会更改。

答案 9 :(得分:0)

这对我有用:

 $.validator.messages.required = 'Your Message For required Fields ...';
 var validator = $("#formComplexe").validate();
 validator.form();

我使用了这个插件:

<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.2/dist/jquery.validate.js"></script>

答案 10 :(得分:0)

以下是语言:https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/localization/

使用 ASP.NET WebForms,我的 from django.urls import path urlpatterns = [ScopedTypeVariables # …, path('pd/<str:df>/<str:dt>/<int:v_id>/<str:interval>/', calc_q), # … ] 中有这个:

Site.Master

请注意本地化文件名以 <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.js" type="text/javascript"></script> <script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/localization/messages_es.js" type="text/javascript"></script> 结尾。然后在 .aspx 文件中:

es

答案 11 :(得分:-2)

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

答案 12 :(得分:-2)

游戏后期,但如果您使用相同的模板进行多种语言,则可以内联:

if($('html').attr('lang')=='he'){
    $('form').validate({
        messages: {
            email:  "חובה",
            phone:  "חובה",
            zip:    "חובה"
        }
    });
}else{
    $('form').validate({
        messages: {
            email:  "Required",
            phone:  "Required",
            zip:    "Required"
        }
    });
};