jQuery client side form validation

1.21K views
no comments
5 Feb 2017 1:54 am

Client side Form validation in Javascript jQuery is best and user-friendly and feature in website, But server side validation is must and required for security reasons. client side form validation can save user time and filled text in fields because if a form don’t have a client side validation form will lost all filled data in form after submission if found validation errors and then user will again fill all of information, So here is text and video base tutorial for form validation.

I have set some of common form fields

These fields are commonly you’ll see registration and signup form from website. TIP-1: I have added for=”” attribute in label tag for user friendly, This will focus user if clicked on label instead field. TIP-2 I have added a required_field class in required form field to and add red border for indicate user this is required field.

preview first stem form validation

<html>
<head>
	<title>jQuery Form Validation</title>
	<link rel="stylesheet" href="style.css" />
	<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
	<script type="text/javascript" src="validation.js"></script>
</head>
<body>
	<div class="form_div">
		<h1>jQuery form validation</h1>
		<form method="post" class="validation_singupform">
			<ul class="form_ul">
				<li>
					<label class="main_label" for="fullname">Full name</label>
					<input type="text" placeholder="Enter full name" name="fullname" id="fullname" class="fullname required_field" />
				</li>
				<li>
					<label class="main_label" for="emailaddress">Email Address</label>
					<input type="text" placeholder="Enter email address" name="emailaddress" id="emailaddress" class="emailaddress required_field" />
				</li>
				<li>
					<label class="main_label" for="password">Passsword</label>
					<input type="password" placeholder="Enter password" name="password" id="password" class="password required_field" />
				</li>
				<li>
					<label class="main_label" for="confirmpassword">Confirm password</label>
					<input type="password" placeholder="Enter password" name="confirmpassword" id="confirmpassword" class="confirmpassword required_field" />
				</li>
				<li>
					<label class="main_label" for="country">Select Country</label>
					<select name="country" id="country" class="country required_field">
						<option value="0">Select country</option>
						<option value="PK">Pakistan</option>
						<option value="IN">Indian</option>
						<option value="USA">United States</option>
						<option value="UK">United Kingdom</option>
					</select>
				</li>
				<li>
					<label class="main_label"> Select Gender</label>
					<label  for="gender_male" class="sel_gender required_field">Male</label>
					<input class="gender_male" name="gender" id="gender_male" value="male" type="radio" />

					<label  for="gender_female" class="sel_gender">Female</label>
					<input class="gender_female" name="gender" id="gender_female" value="female" type="radio" />
				</li>
				<li>
					<label class="main_label" for="write_about">Write about your self</label>
					<textarea class="write_about" name="write_about" id="write_about" placeholder="Write about your self"></textarea>
				</li>
				<li>
					<input type="submit" value="Register" class="register_btn" />

				</li>
			</ul>
		</form>
	</div>
</body>
</html>

Set css selector and properties

In above preview is looking ugly, I am using external css  so create style.css in same folder, so write it in style.css

body{
	font-family:Arial;
	margin:0px;
	padding:0px;
}
.form_div{
	margin: 0 auto;
	display: block;
	width: 80%;
	background-color: #EAEAEA;
	margin-top: 10px;
	padding: 5px 20px;
}
.form_div> h1 {
	width:80%;
	text-align:center;
	color:#B43737;
}
.form_ul {

}
.form_ul > li {
	list-style:none;
	margin:20px 0px;
}

label.main_label {
	width: 200px;
	float: left;
	text-align: right;
	padding: 8px 10px 0px 10px;
	color: #B6B6B6;
	font-size: 14px;
}

label.sel_gender {
	text-align: right;
	padding: 8px 10px 0px 10px;
	color: #B6B6B6;
	font-size: 14px;
}
.form_ul > li input[type=text], .form_ul > li input[type=password], .form_ul > li select {
	border: none;
	padding: 8px 13px;
	width: 250px;
	color: #B3B3B0;
}

.form_ul > li .required_field{
	box-shadow:inset #FF8B79 4px 0px 0px;
}

.form_ul > li textarea {border: none;
	padding: 8px 13px;
	border: none;
	width: 450px;
	height: 150px;
	resize:none;
	color: #B3B3B0;
}
.register_btn{
	padding: 8px 13px;
	border: none;
	width: 189px;
	height: 46px;
	font-weight: bold;
	font-size: 17px;
	color: #B3B3B0;
	margin-left: 220px;
}
.nodisplay{
	display:none;
}

span.text_error_msg {
	color: #AE6D63;
	font-size: 12px;
	clear: both;
	width: 400px;
	margin: 0px 10px;
	font-weight:bold;
}

After adding css form will be look like same as below image
second step preview after adding css

Add jQuery support file and create another validation.js

jquery-1.11.2.min.js download it from jQuery website and create validation.js file for validation, write $(document).ready(function (){ BELOW STEP CODES WILL BE PLACE HERE });

below steps we create functions for each fields. eg: validating Full name field create function validate_fullname

Creates function show_error_msg and remove_error_msg

The show_error_message function will show error message we call it each validation function of field this function have two parameter  with two first parameter used to show error after field, and second parameter is used for to show message eg: please enter valid email address.

The remove_error_msg function will be used if user enter valid email address so we remove error message. This function have one parameter field selector where it will find error message and remove.

function show_error_msg(field_sel,error_msg){
	var error_message_html = '<span class="text_error_msg nodisplay">'+error_msg+'</span>';
	$(field_sel).next('.text_error_msg').remove();
	$(field_sel).after(error_message_html);
	$(field_sel).next('.text_error_msg').fadeIn(700);
}

function remove_error_msg(field_sel_remove){
	$(field_sel_remove).next('.text_error_msg').fadeOut(500,function (){
		$(field_sel_remove).next('.text_error_msg').remove();
	});
}

Validate Full name field

Create function called validate_fullname, in this function define variables, fullname_sel variable is used for selector in fullname_ele variable. fullname_ele_val variable used for value of field which filled by user. This variables process used in other validation functions. If user enter fullname less than or equal to 5 characters then call show_error_message else user enter fullname correctly call remove_error_msg function to remove error message from field.

function validate_fullname(){
	var fullname_sel = '.fullname';
	var fullname_ele = $(fullname_sel);
	var fullname_ele_val = fullname_ele.val();
	if(fullname_ele_val.length <=5){
		show_error_msg(fullname_sel,'please enter fullname atleast 6 characters');
		return false;
	} else {
		remove_error_msg(fullname_sel);
		return true;
	}
}

Call defined function validate_fullname $(‘.fullname’).blur(validate_fullname); see preview in image

preview of called validate_firstname on blur

 

Create function to validate email address with regex

In validate_emailaddress function using regex to validate email. I am describing the bolded letters of regex.
/^[a-zA-Z0-9_.]+\@[a-zA-Z0-9.]+\.[a-zA-Z0-9]{2,4}$/; (First and last slash / is starting and ending point of regex)
/^[a-zA-Z0-9_.]+\@[a-zA-Z0-9.]+\.[a-zA-Z0-9]{2,4}$/; (first word of email which start before @ with the range of small a-zA-Z0-9 dot(.) or (underscore(_)) it support eg:rameez.sdtuts or rameez_sdtuts or rameezsdtuts
/^[a-zA-Z0-9_.]+\@[a-zA-Z0-9.]+\.[a-zA-Z0-9]{2,4}$/; (+ next letter with @ and after @ word must contain domain.com or second bolded part main like support domain eg: domain.com.pk
/^[a-zA-Z0-9_.]+\@[a-zA-Z0-9.]+\.[a-zA-Z0-9]{2,4}$/; ({2,4}Two times or four times $ is end of string)

function validate_emailaddress(){
	var email_sel = '.emailaddress';
	var emailaddress_ele = $(email_sel);
	var emailaddress_ele_val = emailaddress_ele.val();
	var email_regex = /^[a-zA-Z0-9_.]+\@[a-zA-Z0-9.]+\.[a-zA-Z0-9]{2,4}$/;
	if(!emailaddress_ele_val.match(email_regex)){
		show_error_msg(email_sel,'please enter valid email address');
		return false;
	} else {
		remove_error_msg(email_sel);
		return true;
	}
}
$('.emailaddress').blur(validate_emailaddress);

Validate the password field

Create function called validate_passowrd, this function similar to validate_fullname

function validate_password(){
	var password_sel = '.password';
	var password_ele = $(password_sel);
	var password_ele_val = password_ele.val();
	if(password_ele_val.length <=5){
		show_error_msg(password_sel,'please enter password atleast 6 characters');
		return false;
	} else {
		remove_error_msg(password_sel);
		return true;
	}
}
$('.password').blur(validate_password);

Validate confirm password field

create function validate_confirmpassword, this function also similar to confirm password but additional thing in else if confirmpassword must equal to password. The comparison !== mean same text and same text-case like eg: password = mytextpass and confirmpassword= mytextpass it return true and If password = mytextpassword and confirmpassword= mytextPassword it will return false;

function validate_confirmpassword(){
	var confirmpassword_sel = '.confirmpassword';
	var confirmpassword_ele = $(confirmpassword_sel);
	var confirmpassword_ele_val = confirmpassword_ele.val();

	var password_ele_val = $('.password').val();

	if(confirmpassword_ele_val.length <=5){
		show_error_msg(confirmpassword_sel,'please enter confirm password atleast 6 characters');
		return false;
	} else if(password_ele_val!==confirmpassword_ele_val) {
		show_error_msg(confirmpassword_sel,'confirm password not matched with password');
		return false;
	} else{
		remove_error_msg(confirmpassword_sel);
		return true;
	}
}
$('.confirmpassword').blur(validate_confirmpassword);

Validate country field

Create function validate_country in this function two difference from others, first is get the selected option value and I have set value 0 in html on Select country because if I didn’t assign value=”0″ it will return “Select country”.

function validate_country(){
	var country_sel = '.country';
	var country_ele = $(country_sel);
	var country_val = $('.country option:selected').attr('value');
	if(country_val ==0 || typeof country_val==='undefined'){
		show_error_msg(country_sel,'please select country');
		return false;
	} else {
		remove_error_msg(country_sel);
		return true;
	}
}
$('.country').blur(validate_country);

Validate gender field

Create function validate_gender in this function get the checked value if value null or undefined then it return show error.

function validate_gender(){
	var sel_val = $('input[name=gender]:checked').val();
	var error_sel = '.gender_female';
	if(typeof sel_val==='undefined' || sel_val==null){
		show_error_msg(error_sel,'please select gender');
		return false;
	} else {
		remove_error_msg(country_sel);
		return true;
	}
}

I Didn’t validate the write about your self field because this is not required field

Call all defined validation function on form submission

Pass anonymous function when form will be submitted event, in If condition each function will return true it mean all required fields are filled with valid data in else condition to call again function to show errors message on required fields. Note: use form.Class in selector if only tag used form may it will not work.

$('form.validation_singupform').submit(function(){
	if(  validate_country() && validate_confirmpassword() && validate_password() && validate_fullname() && validate_emailaddress() && validate_gender() ){
		return true;
	} else {
		validate_country();
		validate_confirmpassword();
		validate_password();
		validate_fullname();
		validate_emailaddress();
		validate_gender();
		return false;
	}

});

errors of validation after form submission

NOTE:Your Email Address will be not shown and please do not add spamming comments because here is REL="NOFOLLOW" on your links and comments also moderated shown.
<code>Put html css or any language code under this tag</code>