Custom jQuery html form fields validation for all input types

custom jquery form validation example for all input fields

In this tutorial, we have explained about how to do custom jQuery html form fields validation. To implement custom jquery form validation we need a html form with few or more input fields. Have a look on the below example html code for form which is using in this tutorial. Copy this code into your HTML file body tag.

If you observe the below HTML code, each input field code is written in the same format, for some fields it may differ slightly but parent tag “p” and “label” tags are same for all input fields. The “p” tag will be read by jQuery code to append error message.

The below classes are used to define the type of validation.
1. class=”required” is used for empty validation.
2. class=”required email” is used for email validation.
3. class=”required cpass” is used for confirm password validaion.
4. class=”required radio” is for radion button validation.
5. class=”required checkbox” is for checkbox validation.
6. data-error-msg=”” attribute is used to pass custom error message.
7. data-invalid-error-msg=”” attribute is used to pass custom invalid error message.

Css file used for this example. Copy and place in your head tag.

<link href="css/styles.css" rel="stylesheet" type="text/css" />
<div id="container">
	<h1>Custome jQuery form validation demo</h1>
	<div class="login-page">
		<form  action="" name="registerForm" id="registerForm" autocomplete="off" method="POST" onsubmit="return validateForm();"> 
			<h2>Register</h1>
			<p> 
				<label for="firstname" class="uname" > Firstname </label>
				<input id="firstname" name="firstname" type="text" placeholder="Firstname" class="required" data-error-msg="Please enter firstname"/>
			</p>
			<p> 
				<label for="lastname" class="youpasswd"> Lastname </label>
				<input id="lastname" name="lastname" type="text" placeholder="Lastname" class="required" data-error-msg="Please enter lastname" /> 
			</p>
			<p> 
				<label for="email" class="uname" > Email address </label>
				<input id="email" name="email" type="text" placeholder="Enter address" class="required email" data-error-msg="Please enter email address" data-invalid-error-msg="Please enter valid email address"/>
			</p>
			<p> 
				<label for="password" class="uname" > Password </label>
				<input id="password" name="password" type="password" placeholder="Password" class="required" data-error-msg="Please enter password"/>
			</p>
			<p> 
				<label for="cpassword" class="uname" > Confirm password </label>
				<input id="cpassword" name="cpassword" type="password" placeholder="Confirm password" class="required cpass" data-error-msg="Please confirm your password" data-invalid-error-msg="Passwords doesnot match"/>
			</p>
			<P>
				<label for="female">Gender</label>
				<span class="gender">
					<span><input type="radio" class="required radio" id="male" name="gender" value="male" data-error-msg="Please select gender" /> <label for="male">Male</label></span>
					<span><input type="radio" id="female" name="gender" value="female" /> <label for="female">Female</label></span>
				</span>	
			</p>
			<P>
				<label for="habbits">Habbits</label>
				<span class="habbits">
					<span><input type="checkbox" id="cricket" class="required checkbox" name="habbits[]" value="Cricket" data-error-msg="Please select your habbits" /> <label for="cricket">Cricket</label></span>
					<span><input type="checkbox" id="baseball" name="habbits[]" value="Baseball" /> <label for="baseball">Baseball</label></span>
					<span><input type="checkbox" id="soccer" name="habbits[]" value="Soccer" /> <label for="soccer">Soccer</label></span>
				</span>	
			</p>
			<p> 
				<label for="country" class="uname" > Country </label>
				<select class="required" name="country" id="country" data-error-msg="Please select your country">
					<option value="">Please select your country</option>
					<option>Country1</option>
					<option>Country2</option>
					<option>Country3</option>
					<option>Country4</option>
					<option>Country5</option>
					<option>Country6</option>
				</select>
			</p>
			<p> 
				<label for="aboutyou" class="uname" data-icon="u" > About you </label>
				<textarea id="aboutyou" name="aboutyou" cols="53" rows="5" placeholder="About you..." class="required" data-error-msg="Please enter about you"></textarea>
			</p>
			<p class="login button">
				<input type="hidden" name="fAction" value="Register" />
				<input type="submit" value="Login" /> 
			</p>	
		</form>
	</div>
</div>
<script type="text/javascript"  src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="js/customValidate.js"></script>

If you see in the below jQuery code, the very fist line we are reading all required fields which are having a class name as required and storing all the required fields into requiredFields variable. This variable is used in two function in the below code, one is validateForm and the other one is bindFormValidation to iterate each field to pass it for validation.

The other functions like validateField, displayErroMessage, displayInvalidErrorMessage, removeErrorMessage and isEmpty for field validation and to display and remove error messages.

Copy the below code into customValidation.js

var requiredFields = $('form .required');

var regex = { 'email':/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/,
			phone:''}// if you want to do phone number validation add your regex here and make necessary changes in script

// function for empty validation 
var isEmpty = function(value){
	if(value == "")
		return true;
	else
		return false;
}

//Checkbox validaion
var checkBoxValidation = function(obj){
	var check = false;
	if(obj){
		$.each(obj,function(index,checkObj){
			if(checkObj.checked){
				check = true;
			}
		});
	}
	return check;
}

//Check validation when user clicks on submit button
var validateForm = function(){
	if(requiredFields.length){
		$.each(requiredFields,function(index,fieldObj){
			if(fieldObj.type=="checkbox"){
				validateField($("input:checkbox[name='"+fieldObj.name+"']"));
			}else if(fieldObj.type=="radio"){
				validateField($("input:radio[name='"+fieldObj.name+"']"));
			}else{
				validateField(fieldObj);
			}
		});
	}

	if($('.errorMsg').length)
		return false;
	else
		return true;
}
// To remove error message when a field validation is passed
var removeErrorMsg = function(fieldObj){
	var parentElem = $(fieldObj).parents('p');
	
	if($(parentElem).find('.errorMsg').length){
		$(parentElem).find('.errorMsg').remove();
	}
}
// To display error messages
var displayErrorMessage = function(fieldObj){
	var parentElem = $(fieldObj).parents('p');

	if(!$(parentElem).find('.errorMsg').length){
		$(parentElem).append('<div class="errorMsg">'+$(fieldObj).data('errorMsg')+'</div>');
	}
}
// To display invalid error messages
var displayInvalidErrorMessage = function(fieldObj){
	var parentElem = $(fieldObj).parents('p');

	$(parentElem).find('.errorMsg').remove();
	if(!$(parentElem).find('.errorMsg').length){
		
		$(parentElem).append('<div class="errorMsg">'+$(fieldObj).data('invalidErrorMsg')+'</div>');
	}
}

// Validation cases like empty, email, checkbox, radio, etc
var validateField = function(fieldObj){
	var className = $(fieldObj).attr("class");
	switch(className){
		case "required":		
			if(isEmpty($(fieldObj).val())){				
				displayErrorMessage(fieldObj);
			}else{
				removeErrorMsg(fieldObj);
			}
		break;	
		case "required radio":		
			if(!$(fieldObj).prop('checked')){				
				displayErrorMessage(fieldObj);
			}else{
				removeErrorMsg(fieldObj);
			}
		break;	
		case "required checkbox":				
			if(!checkBoxValidation($(fieldObj))){	
				displayErrorMessage(fieldObj);
			}else{
				removeErrorMsg(fieldObj);
			}
		break;	
		case "required email":	
		//alert(regex.email);
			var emailVal = regex.email;
			if(isEmpty($(fieldObj).val())){				
				displayErrorMessage(fieldObj);
			}else if(!emailVal.test($(fieldObj).val())){
				displayInvalidErrorMessage(fieldObj);
			}else{
				removeErrorMsg(fieldObj);
			}
		break;
		case "required cpass":		
			if(isEmpty($(fieldObj).val())){				
				displayErrorMessage(fieldObj);
			}else if($('#password').val() !== $(fieldObj).val()){
				displayInvalidErrorMessage(fieldObj);
			}else{
				removeErrorMsg(fieldObj);
			}
		break;		
	}
}

// While page is loading binding the on blur,click,keyup events
var bindFormValidation = function (){
	if(requiredFields.length){
		$.each(requiredFields,function(index,fieldObj){
			if(fieldObj.type=="checkbox"){
				$("input:checkbox[name='"+fieldObj.name+"']").click(function() {
					validateField($("input:checkbox[name='"+fieldObj.name+"']"));
				});
			}else if(fieldObj.type=="radio"){
				$("input:radio[name='"+fieldObj.name+"']").click(function() {
					validateField(this);
				});
			}else{
				$(fieldObj).bind('blur keyup',function(){
					validateField(fieldObj);
				});
			}
		});
	}
}

bindFormValidation();

Please do comment for any help in the above code. Below are the links for download and demo.

Download / Demo

You may also like...