jQuery validation: change default error message

JqueryJquery Validate

Jquery Problem Overview


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!

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

This worked for me:

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

Solution 4 - Jquery

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

Solution 5 - Jquery

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

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

@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

Solution 9 - Jquery

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

Solution 10 - Jquery

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>

Solution 11 - Jquery

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>

Solution 12 - Jquery

To remove all default error messages use

$.validator.messages.required = "";

Solution 13 - Jquery

$(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;	
	}

});

});

Solution 14 - Jquery

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

		},

});

Solution 15 - Jquery

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKevin BrownView Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryStevenView Answer on Stackoverflow
Solution 3 - JqueryJoshView Answer on Stackoverflow
Solution 4 - JqueryMahmoud FadelView Answer on Stackoverflow
Solution 5 - Jqueryuser1207577View Answer on Stackoverflow
Solution 6 - JqueryGanskeView Answer on Stackoverflow
Solution 7 - JqueryjitterView Answer on Stackoverflow
Solution 8 - JqueryKrolockView Answer on Stackoverflow
Solution 9 - JquerysanjeevView Answer on Stackoverflow
Solution 10 - JqueryStephen SprinkleView Answer on Stackoverflow
Solution 11 - JqueryDeveloperView Answer on Stackoverflow
Solution 12 - JquerydangelView Answer on Stackoverflow
Solution 13 - JqueryJerry131View Answer on Stackoverflow
Solution 14 - Jqueryuser3065103View Answer on Stackoverflow
Solution 15 - JqueryviduraView Answer on Stackoverflow