Add validation to the form with jQuery Validation Plugin

You generally display an error message while validating the form by using the alert or place message on <div> or <span> elements and show or hide them.

If you have a form that has many elements and you need to add Client-side Validation.

You are using the container to show the error messages in this case you need to create several container elements. It is a time-consuming process.

For making your validation process simpler there are many free jQuery plugins.

In this tutorial, I will explain you about Validation jQuery Plugin, using that you can define validation faster and systematic way.

It has the built-in method which you can use for validation and you can change the text of the default error message.

You can also create your own method if you do not find any built-in method according to your requirement.

Add validation to the form with jQuery Validation Plugin


Contents

  1. Download and Include
  2. Implementation Rules
  3. Example
  4. Some Built-in methods
  5. Create custom method
  6. Conclusion

1. Download and Include

  • First include jQuery library.
  • Download the plugin from here and include jquery.validate.min.js script or you can also use CDN.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.3/dist/jquery.validate.min.js"></script>
  • Include the scripts in <head> section.

2. Implementation Rules

This plugin allows you to set rules and error messages on the elements.

For adding validation to the form elements you need to pass or define an object which has rules, messages, and submitHandler property.

rules – Add validation rule to an element. It uses the name of the element for validation.

  • Adding a Single rule to an element

Syntax –

{
  rules: { 
    element-name: method-name,
    element-name: method-name,... 
  }
}
  • Multiple rules to an element

Syntax –

{
  rules: { element-name: { 
      method-name: argument,
      method-name: argument,...           
    },
    element-name: method-name,... 
  }
}

messages – Change the default error message of the rule of the element.

  • On single rule

Syntax –

{
 messages: { 
    element-name: message,
    element-name: message,... 
   }
}
  • Multiple rules

Syntax –

{
  rules: { element-name: { 
      method-name: message1,
      method-name: message2,...           
    },
    element-name: message,... 
  }
}

submitHandler – Call when the form is valid.  Perform operation after form valid or submit it.

{
 submitHandler: function(form) {
   // statements
 }
}

2. Example

For adding validation to the elements it uses name instead of id.

Creating a basic form and adding validation to it.

HTML

<form action="" id='myform' method='post'>
 <table>
  <tr>
   <td>First Name</td>
   <td><input type="text" name="fname" id="fname"/></td>
  </tr>
  <tr>
   <td>Last Name</td>
   <td><input type="text" name="lname" id="lname"/></td>
  </tr>
  <tr>
   <td>Email</td>
   <td><input type="text" name="email" id="email"/></td>
  </tr>
  <tr>
   <td>Age</td>
   <td><input type="text" name="age" id="age"/></td>
  </tr>
  <tr>
   <td>Dob</td>
   <td><input type="text" name="dob" id="dob"/></td>
  </tr>
  <tr>
   <td>Password</td>
   <td><input type='password' name='password' id='password' ></td>
  </tr>
  <tr>
   <td>Retype password</td>
   <td><input type='password' name='retype_password' id="retype_password"></td>
  </tr>
  <tr>
   <td>&nbsp;</td>
   <td><input type='submit' value='Submit' ></td>
  </tr>
 </table>
</form>

CSS

form .error{
 color: red;
}

jQuery

Set the rules and messages on the input element by its names.

$(document).ready(function() {

 $("#myform").validate({
   rules: {
      fname: "required",
      lname: "required",
 
      age: {
        required: true,
        minlength: 2,
        digits: true,
        min: 18,
        max: 40 
      },
      email: {
        required: true,
        email: true,
      },
      dob:{
        date:true
      },
      password: "required",
      retype_password:{
         equalTo: "#password"
      }
   },
   messages: {
      fname: "Please enter your firstname",
      age: {
        number: 'Accept only number',
        minlength: "Atleast 2 digits"
      },
      email: "Please enter a valid email address"
   },
   submitHandler: function(form) {
      return false;
      //    form.submit();
   }
 });
});

 

View Demo


3. Built-in methods –

Some of the built-in methods are –

  • required – Field couldn’t be empty.

Syntax –

rules:{
  element-name: "required"
}
  • email – Check valid email address.

Syntax –

rules:{
  element-name: "email"
}
  • number – Allow to take only decimal values.

Syntax –

rules:{
  element-name: "number"
}
  • digits – Takes digits only.

Syntax –

rules:{
  element-name: "email"
}
  • minlength – Set min length of the element. If the length is less than the given minlength then it shows an error message.

Syntax –

rules:{
  element-name:{ minlength: length }
}
  • maxlength – Set max length of the element. If the length is greater than the given maxlength then it shows an error message.

Syntax –

rules:{
  element-name:{ maxlength: length }
}
  • min – Set minimum value for an element.

Syntax –

rules:{
  element-name:{ min: min-value }
}
  • max – Set maximum value for an element.

Syntax –

rules:{
  element-name:{ max: max-value }
}
  • url – Validate the element to take valid URL.

Syntax –

rules:{
  element-name: "url"
}
  • date – Validate the element to take the valid date.

Syntax –

rules:{
  element-name: "date"
}
  • equalTo – The element should be the same as another one. It takes comparing field id e.g. equalTo: “#password”.

Syntax –

rules:{
  element-name:{ equalTo: element-id }
}

I only explained some of the methods you can find more methods here.


5. Create custom method

You can also define your own custom method which you can use to validate the form.

Syntax –

jQuery.validator.addMethod( name, method [, message ] )

Parameters

name – It is the name of your new custom method.

method – It does logical part and returns true and false according to the condition. It contains two parameters, First parameter is the element value and the second parameter is the validating element.

message – It is optional parameter, from here you can define default error message. If you have not defined this parameter then you need to specify it in validate() method in messages property while adding validation.

Defining new validation

$.validator.addMethod("notIn", function(value, element) {
 if(value == 2|| value == 5 || value == 8){
  return false;
 }else{
  return true;
 }
}, "Enter value other than 2,5, and 8");

Implementing it

$("#myform").validate({
 rules: {
  num: {
    notIn:true,  // custom method
    digits:true,
    max:10
  }
 },
 submitHandler: function(form){
    return false;
    // form.submit();    
 }
});

View Demo


6. Conclusion

I explained you about the jQuery Validation Plugin which helps you to simplify your validation work. It has several built-in methods which you can use and you can also define your own validation rules.

If you found this tutorial helpful then don't forget to share.