380
votes

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!

14

14 Answers

770
votes

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

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

93
votes

This worked for me:

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

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.",
            }
        }
    })
42
votes

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')
    }
    // ...
});
23
votes

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

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(...),
    ...
});
5
votes

@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

4
votes

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  
       });  
   });  
3
votes

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

2
votes

To remove all default error messages use

$.validator.messages.required = "";
1
votes

jQuery Form Validation Custom Error Message -tutsmake

Demo

$(document).ready(function(){
  $("#registration").validate({
    // Specify validation rules
    rules: {
      firstname: "required",
      lastname: "required",
      email: {
        required: true,
        email: true
      },      
      phone: {
        required: true,
        digits: true,
        minlength: 10,
        maxlength: 10,
      },
      password: {
        required: true,
        minlength: 5,
      }
    },
    messages: {
      firstname: {
      required: "Please enter first name",
     },      
     lastname: {
      required: "Please enter last name",
     },     
     phone: {
      required: "Please enter phone number",
      digits: "Please enter valid phone number",
      minlength: "Phone number field accept only 10 digits",
      maxlength: "Phone number field accept only 10 digits",
     },     
     email: {
      required: "Please enter email address",
      email: "Please enter a valid email address.",
     },
    },
  
  });
});
<!DOCTYPE html>
<html>
<head>
<title>jQuery Form Validation Using validator()</title>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<style>
  .error{
    color: red;
  }
  label,
  input,
  button {
    border: 0;
    margin-bottom: 3px;
    display: block;
    width: 100%;
  }
 .common_box_body {
    padding: 15px;
    border: 12px solid #28BAA2;
    border-color: #28BAA2;
    border-radius: 15px;
    margin-top: 10px;
    background: #d4edda;
}
</style>
</head>
<body>
<div class="common_box_body test">
  <h2>Registration</h2>
  <form action="#" name="registration" id="registration">
 
    <label for="firstname">First Name</label>
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>
 
    <label for="lastname">Last Name</label>
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>
 
    <label for="phone">Phone</label>
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  
 
    <label for="email">Email</label>
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>
 
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder=""><br>
 
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">
  </form>
</div>
 
</body>
</html>
0
votes
$(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;   
    }

});

});
-3
votes

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.