You are currently viewing jQuery validation Example

jQuery validation Example

Hello guys, Bushan here, Welcome back to B2 Tech. If we are creating any kind of web application and having a form in the web application is very very common. In such applications, validating a form fields plays a major role, we can validate the form fields in two ways, one is client-side and another one is the server-side. Today in this article, let’s discuss the client-side validation using jQuery validator.




First thing first, In order to work with jQuery validator first we need jQuery core library because the jQuery validator is dependent on jQuery. So first let’s include jQuery core library CDN just before closing the </body> tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

after the jQuery core library, include the jQuery validator CDN

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>

If you are using bootstrap then include the bootstrap core library CDN

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

then finally include our customized js file which holds the jQuery validation

<script src="register.js"></script>

Make sure to include bootstrap core css file in the <head> section if you are using bootstrap

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

jQuery validate function takes two properties, one is rules and another one is messages, inside the rules we will specify the form/input elements name and respective validation like required. In the messages, respective error messages will specify.




Find the complete source code below

register.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>jQuery Validation - Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <style>
  	.error{
    	color: red;
        font-style: italic;
    }
  </style>
</head>
<body>
	<div class = "container">
    	<div class = "col-md-6 col-md-offset-3">
        	<div class = "panel panel-primary">
            	<div class = "panel-heading">
                	Registration
                </div>
                <div class = "panel-body">
                	<form id = "registration">
                    	<input type = "text" class = "form-control" name = "username" placeholder = "Username"/>
                        <br/>
                        <input type = "text" class = "form-control" name = "email" placeholder = "Email"/>
                        <br/>
                        <input type = "password" class = "form-control" name = "password" placeholder = "Password" id = "password"/>
                        <br/>
                        <input type = "password" class = "form-control" name = "confirm" placeholder = "Confirm Password"/>
                        <br/>
                        <input type = "text" class = "form-control" name = "fname" placeholder = "First Name"/>
                        <br/>
                        <input type = "text" class = "form-control" name = "lname" placeholder = "Last Name"/>
                        <br/>
                        <div class = "gender">
							<label class="radio-inline"><input type="radio" name="gender" class = "form-contorl"/>Male</label>
							<label class="radio-inline"><input type="radio" name="gender" class = "form-contorl"/>Female</label>       
                        </div>
                        <br/>
                        
                        <div class = "hobbies">
                        	<label class="checkbox-inline"><input type="checkbox" name = "hobbies">Cricket</label>
							<label class="checkbox-inline"><input type="checkbox" name = "hobbies">Football</label>
							<label class="checkbox-inline"><input type="checkbox" name = "hobbies">Hockey</label>
                        	<label class="checkbox-inline"><input type="checkbox" name = "hobbies">Tennis</label>
                        </div>
                        <br/>
                        <select class = "form-control" name = "country">
                        	<option value="0" selected="" disabled="">--SELECT--</option>
                            <option>India</option>
                            <option>Australia</option>
                            <option>Japan</option>
                            <option>China</option>
                            <option>South Africa</option>
                        </select>
                        <br/>
                        <textarea class = "form-control" name = "address" placeholder="Address"></textarea>
                        <br/>
                        <button type = "submit" class = "btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  	<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="register.js"></script>  
</body>
</html>

register.js

jQuery.validator.addMethod("noSpace", function(value, element) { 
    return value == '' || value.trim().length != 0;  
}, "No space please and don't leave it empty");
jQuery.validator.addMethod("customEmail", function(value, element) { 
  return this.optional( element ) || /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test( value ); 
}, "Please enter valid email address!");
$.validator.addMethod( "alphanumeric", function( value, element ) {
return this.optional( element ) || /^\w+$/i.test( value );
}, "Letters, numbers, and underscores only please" );
var $registrationForm = $('#registration');
if($registrationForm.length){
  $registrationForm.validate({
      rules:{
          //username is the name of the textbox
          username: {
              required: true,
              //alphanumeric is the custom method, we defined in the above
              alphanumeric: true
          },
          email: {
              required: true,
              customEmail: true
          },
          password: {
              required: true
          },
          confirm: {
              required: true,
              equalTo: '#password'
          },
          fname: {
              required: true,
              noSpace: true
          },
          lname: {
              required: true,
              noSpace: true
          },
          gender: {
              required: true
          },
          hobbies: {
              required: true
          },
          country: {
              required: true
          },
          address: {
              required: true
          }
      },
      messages:{
          username: {
              //error message for the required field
              required: 'Please enter username!'
          },
          email: {
              required: 'Please enter email!',
              //error message for the email field
              email: 'Please enter valid email!'
          },
          password: {
              required: 'Please enter password!'
          },
          confirm: {
              required: 'Please enter confirm password!',
              equalTo: 'Please enter same password!'
          },
          fname: {
              required: 'Please enter first name!'
          },
          lname: {
              required: 'Please enter last name!'
          },
          country: {
              required: 'Please select country!'
          },
          address: {
              required: 'Please enter address!'
          }
      },
      errorPlacement: function(error, element) 
      {
        if (element.is(":radio")) 
        {
            error.appendTo(element.parents('.gender'));
        }
        else if(element.is(":checkbox")){
            error.appendTo(element.parents('.hobbies'));
        }
        else 
        { 
            error.insertAfter( element );
        }
        
       }
  });
}

That’s it now open the register.html click the submit button without entering anything, it will display the error messages.




Below is the quick demo of the example

You can download the example from the below links,




Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

Leave a Reply