Conditional Validation with Jquery Validator

Posted On: 28 Nov, 2017      Category: Javascript

People make mistakes when they fill out any form. By validating a form, we can alert to users of their errors before they submit the form. Thus, client side form validation can improve nice user experience on your website. This article will explain basics and conditional form validation in JavaScript using the plugin jQuery Validator.

There is a common case that validations of fields depend on value of an element or additional conditions. For example, when you stop using software or an online service, you might be asked for the reason. You can pick one from the given list, or choose a kind of "Other" checkbox. In the case that checkbox is selected, you have to indicate the specific reason. The reason is only required if you don't choose given one. But here, going to take another example for you.

Suppose, you have to update mobile, email or address as you choose option from drop-down options. You can update one from these.

First of all, you need to include jQuery library which can be downloaded from jQuery Website. You can also use CDN which is also available there.

Now, download jQuery Validator  plugin from https://jqueryvalidation.org/.

Create an html file with name example.html and put below HTML code in your html file and include jQuery library and jQuery validator plugin under <head></head> tag as below:

Note:- Here CDN is used for jQuerty library. You can download and include this.

<script  src="https://code.jquery.com/jquery-3.2.1.min.js"  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="  crossorigin="anonymous"></script>
 <script src="js/jquery.validate.min.js" type="text/javascript"></script>

Now, for creating HTML Form put below code under body tag.

<form class="form-horizontal" id="jQuery-conditional-form">
<div class="container">
<!-- Form Name -->
<h1 class="text-center">Conditional Validation With jQuery Validator</h1>
<br>
<br>
<div class="container">
<div class="form-group">
  <label class="col-md-4 control-label" for="name">Your Name</label>  
  <div class="col-md-4">
  <input id="name" name="name" type="text" placeholder="Your Name" class="form-control input-md">  
  </div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="requestType">Request For</label>  
  <div class="col-md-4">
	  <select name="requestType" id="requestType" class="form-control input-md">
		<option value="">Select Request</option>
		<option value="1">Change Address</option>
		<option value="2">Change Email</option>
		<option value="3">Change Mobile Number</option>
	  </select>
  </div>
</div>
  </div>
<div class="container" id="request1" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="corres_addr">Address</label>  
	  <div class="col-md-4">
	  <input id="corres_addr" name="corres_addr" type="text" placeholder="Address" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="state">State</label>  
	  <div class="col-md-4">
	  <input id="state" name="state" type="text" placeholder="State" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="zipcode">Zip Code</label>  
	  <div class="col-md-4">
	  <input id="zipcode" name="zipcode" type="text" placeholder="Zip Code" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="country">Country</label>  
	  <div class="col-md-4">
	  <input id="country" name="country" type="text" placeholder="Country" class="form-control input-md">  
	  </div>
	</div>
</div>
<div class="container" id="request2" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="email">Email</label>  
	  <div class="col-md-4">
	  <input id="email" name="email" type="text" placeholder="Email" class="form-control input-md">  
	  </div>
	</div>
</div>
<div class="container" id="request3" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="mobileno">Mobile No.</label>  
	  <div class="col-md-4">
	  <input id="mobileno" name="mobileno" type="text" placeholder="Mobile No." class="form-control input-md">  
	  </div>
	</div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton">&nbsp;</label>
  <div class="col-md-4">
    <button id="submit" name="submit" class="btn btn-primary">Submit</button>
  </div>
</div>
</div>
</form>

In this form, there is a drop-down for selecting  Request Type  that has three options whenever we select any one option, corresponding container become visible. So, only need to validate visible element on the basis of selected option.Therefore, put below code for show or hide elements or container under <heqad></head> tag and below included plugins.

<script>
$(document).ready(function(){
	$("#requestType").change(function(){
		var currentRequest = $(this).val();
		var options = $('#requestType option');
		var values = $.map(options ,function(option) {
			return option.value;
		});
		$.each(values, function(i, v){
			$("#request"+v).hide();
		});
		$("#request"+currentRequest).show();
	});
});
</script>

In the below code,validate() function is used to validate the form and depends Attribute is used for conditional validation with respect to validation attribute when we use jQuery Validator Plugin. Elements that have to validate depend upon the value of drop-down Request Type. 

<script>
$(document).ready(function(){
	$("#requestType").change(function(){
		var currentRequest = $(this).val();
		var options = $('#requestType option');
		var values = $.map(options ,function(option) {
			return option.value;
		});
		$.each(values, function(i, v){
			$("#request"+v).hide();
		});
		$("#request"+currentRequest).show();
	});
	$("#jQuery-conditional-form").validate({
		rules: {
			name: {
				required: true,
				minlength: 2
			},
			requestType: {
				required: true
			},
			corres_addr: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			state: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 2, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			zipcode: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				digits: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			country: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
			},
			email: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				},
				minlength: {
					param: 6, 
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				},
				email: {
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				}
			},
			mobileno: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				},
				maxlength: {
					param: 10, 
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				},
				digits: {
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				}
			},
		}		
	});
});
</script>

So, you can merge all code as below:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta name=viewport content="width=device-width, initial-scale=1">
  <title>Conditional Validation With jQuery Validator</title>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
  <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="js/jquery.validate.min.js" type="text/javascript"></script>
  </head>
<style>
.error{color:red;}
</style>
<script>
$(document).ready(function(){
	$("#requestType").change(function(){
		var currentRequest = $(this).val();
		var options = $('#requestType option');
		var values = $.map(options ,function(option) {
			return option.value;
		});
		$.each(values, function(i, v){
			$("#request"+v).hide();
		});
		$("#request"+currentRequest).show();
	});
	$("#jQuery-conditional-form").validate({
		rules: {
			name: {
				required: true,
				minlength: 2
			},
			requestType: {
				required: true
			},
			corres_addr: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			state: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 2, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			zipcode: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				digits: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				}
			},
			country: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
				minlength: {
					param: 3, 
					depends: function(element) {
					  return ($("#requestType").val() == 1);
					}
				},
			},
			email: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				},
				minlength: {
					param: 6, 
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				},
				email: {
					depends: function(element) {
					  return ($("#requestType").val() == 2);
					}
				}
			},
			mobileno: {
				required: {
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				},
				maxlength: {
					param: 10, 
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				},
				digits: {
					depends: function(element) {
					  return ($("#requestType").val() == 3);
					}
				}
			},
		}		
	});
});
</script>
</head>
<body>
<form class="form-horizontal" id="jQuery-conditional-form">
<div class="container">
<!-- Form Name -->
<h1 class="text-center">Conditional Validation With jQuery Validator</h1>
<br>
<br>
<div class="container">
<div class="form-group">
  <label class="col-md-4 control-label" for="name">Your Name</label>  
  <div class="col-md-4">
  <input id="name" name="name" type="text" placeholder="Your Name" class="form-control input-md">  
  </div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="requestType">Request For</label>  
  <div class="col-md-4">
	  <select name="requestType" id="requestType" class="form-control input-md">
		<option value="">Select Request</option>
		<option value="1">Change Address</option>
		<option value="2">Change Email</option>
		<option value="3">Change Mobile Number</option>
	  </select>
  </div>
</div>
  </div>
<div class="container" id="request1" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="corres_addr">Address</label>  
	  <div class="col-md-4">
	  <input id="corres_addr" name="corres_addr" type="text" placeholder="Address" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="state">State</label>  
	  <div class="col-md-4">
	  <input id="state" name="state" type="text" placeholder="State" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="zipcode">Zip Code</label>  
	  <div class="col-md-4">
	  <input id="zipcode" name="zipcode" type="text" placeholder="Zip Code" class="form-control input-md">  
	  </div>
	</div>	
	<div class="form-group">
	  <label class="col-md-4 control-label" for="country">Country</label>  
	  <div class="col-md-4">
	  <input id="country" name="country" type="text" placeholder="Country" class="form-control input-md">  
	  </div>
	</div>
</div>
<div class="container" id="request2" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="email">Email</label>  
	  <div class="col-md-4">
	  <input id="email" name="email" type="text" placeholder="Email" class="form-control input-md">  
	  </div>
	</div>
</div>
<div class="container" id="request3" style="display:none;">
	<div class="form-group">
	  <label class="col-md-4 control-label" for="mobileno">Mobile No.</label>  
	  <div class="col-md-4">
	  <input id="mobileno" name="mobileno" type="text" placeholder="Mobile No." class="form-control input-md">  
	  </div>
	</div>
</div>

<div class="form-group">
  <label class="col-md-4 control-label" for="singlebutton">&nbsp;</label>
  <div class="col-md-4">
    <button id="submit" name="submit" class="btn btn-primary">Submit</button>
  </div>
</div>
</div>
</form>
</body>
</html>

Note: Bootstrap plugin is used only for design purpose.

Hope this will help you to implement validation.

You may like: