Client Side Form Validation Using jQuery Validation Plugin

Share this Article
Reading Time: 6 minutes
700 Views

Adding Validations are very important to form either from client side or from server side. To validate a form at client side, we have a popular jquery plugin for it. You can check the complete documentation here.

Simple syntax to use it

$("#form-id").validate();

Sometimes adding form validation rules, we need some custom validators i.e custom rule. To create custom rule we have addMethod() provided by jQuery validation plugin.

$.validator.addMethod("rule", function(){});

Inside this article we will see complete guide to Client Side Form Validation Using jQuery Validation Plugin.

Let’s get started.


How To Use jQuery Validation Plugin ?

To use jquery validation plugin, we need to follow few steps as given below –

  • Download & Setup validation plugin files.
  • Bind Form selector with plugin validate() method.

Let’s see usage of jquery validation plugin step by step by making a simple form.

<html>
	
	<head>
		<style>
			#frm-add-data label.error{
				color:red;
			}
		</style>
	</head>

	<body>
		
		<form action="ACTION_URL" method="post" id="frm-add-data">
			
			<p>
				Name: <input type="text" required name="name" placeholder="Enter name">
			</p>

			<p>
				Email: <input type="email" required name="email" placeholder="Enter email">
			</p>

			<p>
				Mobile: <input type="text" required name="mobile" placeholder="Enter mobile">
			</p>

			<p>
				<button type="submit">Submit</button>
			</p>

		</form>

		<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
		<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.2/jquery.validate.min.js"></script>

		<script>
			
			$(function(){

				// First: Add with default messages
				//$("#frm-add-data").validate();				

				// Second: Change default messages
				$("#frm-add-data").validate({
                	rules: { // to define rules
                		name: "required",
                		email: "required",
                		mobile: {
                			required: true,
            				maxlength: 10
                		}
                	},
                    messages:{ // to define custom messages
                    	name: "Enter your name",
                    	email: "Enter your email",
                    	mobile: {
				            required: "Enter mobile",
				            maxlength: "Enter maximum 10 digits"
				        }
                    },
                    submitHandler: function(){
                    	// when no errors
                    }
                });
			});
		</script>

	</body>

</html>

How to Add Custom Validation Rules

Suppose we want to create some custom rules for mobile input field. Custom rules as –

  • Mobile number should not start with digits like 0, 1, 2, 3, 4.
  • Mobile number length must be equals to 10 digits.
  • To check mobile number already registered via Ajax request.

As we have discussed above, to define custom rules for input fields we use

$.validator.addMethod("rule", "callback");

When we define any rule and suppose it returns false value as it’s return type then meaning we have validation error. Let’s see in action.

Mobile number should not start with digits like 0, 1, 2, 3, 4.

$(function(){

	// Mobile First digit check
	$.validator.addMethod("mobile_inital_digit_check", function(value, element) {

	  if( !value.startsWith("0") && 
          !value.startsWith("1") && 
          !value.startsWith("2") && 
          !value.startsWith("3") && 
          !value.startsWith("4")){
        return true;
      }else{
        return false;
      }
	  
	}, "Invalid mobile number format");
});
  • Rule name – mobile_inital_digit_check
  • Default message returned in case of error: Invalid mobile number format

Add this custom rule to validate() method –

$("#frm-add-data").validate({
  rules : {
    mobile : { 
      mobile_inital_digit_check : true
    }
  },
  submitHandler: function () {
     // rules passed
  }
});

Mobile number length must be equals to 10 digits

$(function(){

	// Mobile number length
	$.validator.addMethod("mobile_number_length", function(value, element) {

      if(value.length == 10){
        return true;
      }else{
        return false;
      }

    }, "Invalid Mobile number length");
    
});

Implementation of Rule

$(function(){

	$("#frm-add-data").validate({
        rules : {
            mobile : { 
                mobile_number_length : true
            }
        },
        submitHandler: function () {
	      // rules passed
        }
    });
});

To check mobile number already registered via Ajax request

$(function(){

	// Rule for Mobile already registered
	$.validator.addMethod("mobile_already_registered", function(value, element) {

       var postdata = "mobile="+value; 
       var is_exists;

       // site_url is the application url
       $.ajax({
         url: site_url + "/check-user-mobile",
         data: postdata,
         dataType: "json",
         async: false,
         success: function(response){

           is_exists = ( response.sts == 1 ) ? true : false;
         }
       });

       return is_exists;

    }, "Mobile number already registered");

});

Implementation of Rule

$(function(){

	$("#frm-add-data").validate({
        rules : {
            mobile : { 
                mobile_already_registered : true
            }
        },
        submitHandler: function () {
        	// rules passed
        }
    });
});

We hope this article helped you to learn about Client Side Form Validation Using jQuery Validation Plugin in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Learn More about jQuery & Javascript Concept

Leave a Comment