How to do Form Validation using Jquery?

Form Validation using Jquery

<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.slim.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script> </head>

We will see the Jquery validation for below sample form.

form validation
HTML:
Required HTML codes for above form design.


<form>
<input name="firstname" type="text" value="firstname" />
<input name="lastname" type="text" value="lastname" />
<input name="email" type="email" value="email" />
<input type="button" value="submit" />
</form>
 

Add below CSS to differentiate the validation messages.

CSS:


.error { 
border: 1px solid #b94a48; 
background-color: #fee; 
}
 

Script:


$(document).ready(function(){
  $(function() {
  // Setup form validation on the #register-form element
 $("#register-form").validate({   //#register-form is form id
     // Specify the validation rules
rules: {
         firstname: "required", //firstname is corresponding input name
         lastname: "required",  //lastname:  is corresponding input name
         email: {               //email is corresponding input name
             required: true,
             email: true
         },
     },
     // Specify the validation error messages
messages: {
         firstname: "Enter First Name",
         lastname: "Enter Last Name",
         email: "Enter Valid Email ID",
         agree: "Please accept our policy"
     },
     submitHandler: function(form) {
         form.submit();
     }
 });

  });
})
 

Explanation:
By using validate method we can define two arrays like rules and messages. In the rules, we can set the validation conditions to accept the given input. In the messages part, we should define the validation messages to show when the user entered the detail wrongly.

You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *