jQuery 验证:更改默认错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2457032/
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 13:33:19  来源:igfitidea点击:

jQuery validation: change default error message

jqueryjquery-validate

提问by Kevin Brown

Is there a simple way to change the default error values in the jQuery validation plugin?

是否有一种简单的方法可以更改jQuery 验证插件中的默认错误值?

I just want to rewrite the error messages to be more personal to my app--I have a lot of fields, so I don't want to set the message individually for field x...I know I can do that!

我只想重写错误消息,使其对我的应用程序更加个性化——我有很多字段,所以我不想为字段 x 单独设置消息......我知道我可以做到!

回答by Nick Craver

Add this code in a separate file/script included afterthe validation plugin to override the messages, edit at will :)

将此代码添加到验证插件之后包含的单独文件/脚本中以覆盖消息,随意编辑:)

jQuery.extend(jQuery.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.",
    creditcard: "Please enter a valid credit card number.",
    equalTo: "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("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("Please enter a value less than or equal to {0}."),
    min: jQuery.validator.format("Please enter a value greater than or equal to {0}.")
});

回答by Steven

You can specify your own messages in the validate call. Lifting and abbreviating this code from the Remember the Milk signup form used in the Validation plugin documentation (http://jquery.bassistance.de/validate/demo/milk/), you can easily specify your own messages:

您可以在验证调用中指定您自己的消息。从验证插件文档 ( http://jquery.bassistance.de/validate/demo/milk/) 中使用的记住牛奶注册表单中提取和缩写此代码,您可以轻松指定自己的消息:

var validator = $("#signupform").validate({
    rules: {
        firstname: "required",
        lastname: "required",
        username: {
            required: true,
            minlength: 2,
            remote: "users.php"
        }
    },
    messages: {
        firstname: "Enter your firstname",
        lastname: "Enter your lastname",
        username: {
            required: "Enter a username",
            minlength: jQuery.format("Enter at least {0} characters"),
            remote: jQuery.format("{0} is already in use")
        }
    }
});

The complete API for validate(...) : http://jqueryvalidation.org/validate

validate(...) 的完整 API:http: //jqueryvalidation.org/validate

回答by Josh

This worked for me:

这对我有用:

$.validator.messages.required = 'required';

回答by Mahmoud Fadel

This worked for me:

这对我有用:

// Change default JQuery validation Messages.
$("#addnewcadidateform").validate({
        rules: {
            firstname: "required",
            lastname: "required",
            email: "required email",
        },
        messages: {
            firstname: "Enter your First Name",
            lastname: "Enter your Last Name",
            email: {
                required: "Enter your Email",
                email: "Please enter a valid email address.",
            }
        }
    })

回答by user1207577

Since we're already using JQuery, we can let page designers add custom messages to the markup rather than the code:

由于我们已经在使用 JQuery,我们可以让页面设计者将自定义消息添加到标记而不是代码中:

<input ... data-msg-required="my message" ...

Or, a more general solution using a single short data-msg attribute on all fields:

或者,在所有字段上使用单个短 data-msg 属性的更通用的解决方案:

<form id="form1">
    <input type="text" id="firstName" name="firstName" 
        data-msg="Please enter your first name" />
    <br />
    <input type="text" id="lastName" name="lastName" 
        data-msg="Please enter your last name" />
    <br />
    <input type="submit" />
</form>

And the code then contains something like this:

然后代码包含如下内容:

function getMsg(selector) {
    return $(selector).attr('data-msg');
}

$('#form1').validate({
    // ...
    messages: {
        firstName: getMsg('#firstName'),
        lastName: getMsg('#lastName')
    }
    // ...
});

回答by Ganske

Another possible solution is to loop over the fields, adding the same error message to each field.

另一种可能的解决方案是遍历字段,向每个字段添加相同的错误消息。

$('.required').each(function(index) {
  $(this).rules("add", {
    messages: {
      required: "Custom error message."
   }
  });
});

回答by jitter

Instead of changing the plugin source code you can include an additional js file in the format like those in the downloads localization folder and include that one after loading the validation.js

无需更改插件源代码,您可以包含一个额外的 js 文件,其格式类似于下载本地化文件夹中的格式,并在加载了 validation.js 后包含该文件

jQuery.extend(jQuery.validator.messages, {
    required: ...,
    maxlength: jQuery.validator.format(...),
    ...
});

回答by Krolock

@Josh: You can expand your solution with translated Message from your resource bundle

@Josh:您可以使用资源包中的翻译消息扩展您的解决方案

<script type="text/javascript">
    $.validator.messages.number = '@Html.Raw(@Resources.General.ErrorMessageNotANumber)';
</script>

If you put this code part into your _Layout.cshtml (MVC) it's available for all your views

如果您将此代码部分放入您的 _Layout.cshtml (MVC),它可用于您的所有视图

回答by sanjeev

I never thought this would be so easy , I was working on a project to handle such validation.

我从没想过这会这么容易,我正在做一个项目来处理这样的验证。

The below answer will of great help to one who want to change validation message without much effort.

下面的答案对那些想要毫不费力地更改验证消息的人有很大帮助。

The below approaches uses the "Placeholder name" in place of "This Field".

以下方法使用“占位符名称”代替“此字段”。

You can easily modify things

你可以很容易地修改东西

   // Jquery Validation   
   $('.js-validation').each(function(){

       //Validation Error Messages 

       var validationObjectArray = [];

       var validationMessages = {};

       $(this).find('input,select').each(function(){  // add more type hear

          var singleElementMessages = {};

          var fieldName = $(this).attr('name');

          if(!fieldName){  //field Name is not defined continue ;
              return true;
          }


          // If attr data-error-field-name is given give it a priority , and then to placeholder and lastly a simple text

          var fieldPlaceholderName = $(this).data('error-field-name') || $(this).attr('placeholder') || "This Field";

          if( $( this ).prop( 'required' )){

              singleElementMessages['required'] = $(this).data('error-required-message') || $(this).data('error-message')  || fieldPlaceholderName + " is required";

          }

          if( $( this ).attr( 'type' ) == 'email' ){

              singleElementMessages['email'] = $(this).data('error-email-message') || $(this).data('error-message')  || "Enter valid email in "+fieldPlaceholderName;

          }       



          validationMessages[fieldName] = singleElementMessages;

       });


       $(this).validate({
          errorClass   : "error-message",
          errorElement : "div",
          messages     : validationMessages  
       });  
   });  

回答by Stephen Sprinkle

The newest version has some nice in-line stuff you can do.

最新版本有一些不错的内联东西你可以做。

If it's a simple input field you can add the attribute data-validation-error-msglike this --

如果它是一个简单的输入字段,您可以data-validation-error-msg像这样添加属性——

data-validation-error-msg="Invalid Regex"

If you need something a little heavier you can fully customize things using a variable with all the values which is passed into the validate function. Reference this link for full details -- https://github.com/victorjonsson/jQuery-Form-Validator#fully-customizable

如果你需要一些更重的东西,你可以使用一个变量来完全自定义东西,所有的值都传递给验证函数。有关完整详细信息,参考此链接 -- https://github.com/victorjonsson/jQuery-Form-Validator#fully-customizable