Every developer uses validations for HTML forms and its better to use plugins instead of custom validations because this way we will not only save time, but also will have some efficient script.
jQuery Validation plugin is a a best and simple validation plugin which you can use for your projects. In this post I will show you how we can use custom error messages instead of default error messages sent from plugin.
Below HTML code shows a form with 3 fields first name, last name & email address.
1 2 3 4 5 6 |
<form id="your_form_id" action="" method="POST" name="your_form_id"> <input id="first_name" class="required" name="first_name" type="text" placeholder="" /> <input id="last_name" class="required" name="last_name" type="text" placeholder="" /> <input id="email_address" class="required" name="email_address" type="text" placeholder="" /> <button id="" class="" type="submit"></button> </form> |
In errorPlacement function, we will embed the custom error messages where ever we will want to show them on the form. The following function is showing the text error messages as placeholder inside the text field.
1 2 3 4 5 6 7 8 9 10 11 12 |
errorPlacement: function(error, element) { // name attrib of the field var n = element.attr("name"); if (n == "first_name") element.attr("placeholder", "Please enter your first name"); else if (n == "last_name") element.attr("placeholder", "Please enter your last name"); else if (n == "email_address") element.attr("placeholder", "Please enter your email address"); } |
We can highlight the input field on errors and we have highlight: function (), in which we will add a class to the input field with error.
We have defined a css class which we will append to the input field if there is any validation error. It will turns the background color of field into red.
1 |
.has_error{ background: red;} |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
$("#your_form_id").validate({ errorPlacement: function(error, element) { // name attrib of the field var n = element.attr("name"); if (n == "first_name") element.attr("placeholder", "Please enter your first name"); else if (n == "last_name") element.attr("placeholder", "Please enter your last name"); else if (n == "email_address") element.attr("placeholder", "Please enter your email address"); }, rules: { first_name: { minlength: 2, required: true }, last_name: { minlength: 2, required: true }, email_address: { minlength: 6, required: true, email: true } }, highlight: function(element) { // add a class "has_error" to the element $(element).addClass('has_error'); }, unhighlight: function(element) { // remove the class "has_error" from the element $(element).removeClass('has_error'); }, submitHandler: function(form) { // submit form now. } }); |
Output: