397

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

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!

SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
Kevin Brown
  • 12,602
  • 34
  • 95
  • 155

14 Answers14

788

Add this code in a separate file/script included after the 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}.")
});
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • @Kevin - Not really...you have to at least set the variables, which is all this is doing. You can include this in the page, in another `.js`, whatever method you want to run the script after the plugin to set the messages. – Nick Craver Mar 16 '10 at 18:47
  • 36
    Worked great. I just added: $.extend($.validator.messages, { required: "Required" }); – Ravi Ram Jul 01 '11 at 21:28
  • Thanks, I always forget to use extend, I might have to start my own jquery plugins to drill it in! – dead Apr 29 '12 at 08:27
  • 7
    I used this as a quick fix for a multilanguage form: if($('body').attr('lang')=="es"){ jQuery.extend... }; – Heraldmonkey Jun 18 '13 at 14:14
  • 5
    @NickCraver, just wanted to say that I never expected to generate so many upvotes with this question...and well done for a timely and quick answer! – Kevin Brown Jul 12 '13 at 03:04
  • 5
    Not working sorry. No message is shown , just required message is shown though i used minlength. – Pratik Joshi Mar 18 '15 at 12:10
  • 2
    Checkout all translation keys on [github](https://github.com/jquery-validation/jquery-validation/tree/master/src/localization) – Bruno Peres Mar 15 '17 at 00:25
  • 2
    Can we include form element name in error message. Instead of only general message. i.e _Login field is required_ instead of _This field is required_ – Musaddiq Khan Jul 25 '17 at 12:32
  • Is it possible to only have a custom validation message to a specific field then the rest will have the default? – Jeda Dragon Aug 12 '21 at 15:28
  • I am getting console error as `Cannot read properties of undefined (reading 'messages')` – Eatsam ul haq Oct 28 '22 at 07:02
259

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:

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

Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49
Steven
  • 3,813
  • 2
  • 22
  • 27
102

This worked for me:

$.validator.messages.required = 'required';
Josh
  • 8,329
  • 4
  • 36
  • 33
  • $.validator.messages.maxlength = jQuery.validator.format("Please enter no more than {0} characters."); does not work. I sugges using Nick Cravers solution instead. – Vidar Vestnes May 21 '14 at 11:44
  • 1
    @VidarVestnes The solution works for your scenario too. You just specify the format string, and the plugin does the rest: `$.validator.messages.maxlength = "Please enter no more than {0} characters.";` – rusmus Sep 29 '14 at 11:37
51

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.",
            }
        }
    })
Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Mahmoud Fadel
  • 511
  • 4
  • 2
  • Note that even if this answer is for jqueryValidation and not jqueryFileUpload, there is also the `messages` options in the `$().fileupload` function. – Xavier Portebois Oct 09 '14 at 07:26
43

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

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

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

<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')
    }
    // ...
});
user1207577
  • 699
  • 6
  • 5
  • This is a great strategy, especially if you need a dynamic message set not in your js files... – Charles Harmon Jul 01 '15 at 20:02
  • @user1207577, Yes we can set the custom messages but how can we display the min length and max length message. I mean If we set the custom then min and max message not displaying.Any Idea? – Naren Verma Sep 10 '17 at 03:09
24

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."
   }
  });
});
Ganske
  • 378
  • 2
  • 6
  • 1
    This solution was exactly what I was looking for...in my scenario every form field has a label, so I find its corresponding label and prepend that to the message so in the end it says "First Name is required." Very nice, Ganske. – tjans Jan 09 '13 at 15:10
  • 2
    +1 While all of the other answers are valid, this is the syntax I was looking for. – scott.korin Mar 04 '13 at 12:53
8

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

jQuery.extend(jQuery.validator.messages, {
    required: ...,
    maxlength: jQuery.validator.format(...),
    ...
});
jitter
  • 53,475
  • 11
  • 111
  • 124
  • It isn't. It is technically the same as your answer. I posted my comment to the old version of your answer. Then wrote my own answer. All without continuously reload the page. Thus I only saw you edited answer when checking your comment – jitter Mar 16 '10 at 18:35
5

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

<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

Krolock
  • 59
  • 1
  • 5
4

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-msg like this --

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

Stephen Sprinkle
  • 1,015
  • 11
  • 14
  • 2
    This is a different plugin than the jQuery Validation Plugin the OP asked about. Not a bad choice though, particularly if placing validation-related data (rules, messages) in the HTML appeals to you (the jQuery Validation Plugin takes the opposite way, using Javascript for all of that). To mention another alternative for the record, Parsley.js is another much used and full-featured validation plugin that relies on HTML attributes. – Endre Both Mar 20 '15 at 21:00
4

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  
       });  
   });  
sanjeev
  • 4,405
  • 2
  • 19
  • 27
  • 1
    Thank you for sharing this. The use of "errorClass" and "errorElement" is genius! I can now apply the styling and location of my error messages created from the validation! – justdan23 Apr 02 '20 at 16:59
2

To remove all default error messages use

$.validator.messages.required = "";
dangel
  • 7,238
  • 7
  • 48
  • 74
0
$(function() {

$("#username_error_message").hide();
$("#password_error_message").hide();
$("#retype_password_error_message").hide();
$("#email_error_message").hide();

var error_username = false;
var error_password = false;
var error_retype_password = false;
var error_email = false;

$("#form_username").focusout(function() {

    check_username();
    
});

$("#form_password").focusout(function() {

    check_password();
    
});

$("#form_retype_password").focusout(function() {

    check_retype_password();
    
});

$("#form_email").focusout(function() {

    check_email();
    
});

function check_username() {

    var username_length = $("#form_username").val().length;
    
    if(username_length < 5 || username_length > 20) {
        $("#username_error_message").html("Should be between 5-20 characters");
        $("#username_error_message").show();
        error_username = true;
    } else {
        $("#username_error_message").hide();
    }

}

function check_password() {

    var password_length = $("#form_password").val().length;
    
    if(password_length < 8) {
        $("#password_error_message").html("At least 8 characters");
        $("#password_error_message").show();
        error_password = true;
    } else {
        $("#password_error_message").hide();
    }

}

function check_retype_password() {

    var password = $("#form_password").val();
    var retype_password = $("#form_retype_password").val();
    
    if(password !=  retype_password) {
        $("#retype_password_error_message").html("Passwords don't match");
        $("#retype_password_error_message").show();
        error_retype_password = true;
    } else {
        $("#retype_password_error_message").hide();
    }

}

function check_email() {

    var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);

    if(pattern.test($("#form_email").val())) {
        $("#email_error_message").hide();
    } else {
        $("#email_error_message").html("Invalid email address");
        $("#email_error_message").show();
        error_email = true;
    }

}

$("#registration_form").submit(function() {
                                        
    error_username = false;
    error_password = false;
    error_retype_password = false;
    error_email = false;
                                        
    check_username();
    check_password();
    check_retype_password();
    check_email();
    
    if(error_username == false && error_password == false && error_retype_password == false && error_email == false) {
        return true;
    } else {
        return false;   
    }

});

});
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56
Jerry131
  • 1
  • 1
-1

To add custom or field label or anything dynamic related to field being validated. you can pick anything through dom and add it anywhere with error message.

below is an example to add field label in start of required message instead of "this field".

jQuery.extend(jQuery.validator.messages, {

    required: function(result,e){

        let field_label = "This field ";

        if($(e).closest('.form-group').find('label').length > 0)
            field_label = $(e).closest('.form-group').find('label').html();

        return field_label+" is required.";

        },

});
-3

instead of these custom error messages we can specify the type of the text field.

Ex: set type of the field in to type = 'email'

then plugin will identify the field and validate correctly.

vidura
  • 65
  • 1
  • 1
  • 7
  • he don't ask to validate it correctly, he ask to rewrite the messages.... "I just want to rewrite the error messages to be more personal to my app" – Benoit Feb 21 '17 at 22:12