Building Real-Time Form Validation Using jQuery

Posted in Coding, Tutorials • Posted on 69 Comments

Building Real-Time Form Validation Using jQueryClient-side validation is something every web form should have, no doubts about that. While server-side validation does its job, it certainly lacks good user experience. What is so great about client-side validation then?

Not only is it useful to the user because it makes the process of filling out the form a lot quicker and a lot less painful, but it also shows that you actually care about them. For the user there’s nothing better than knowing right away if they’re doing it correctly.

In this tutorial we’re going to learn how to build real-time form validation using jQuery. If you’d like to see what you’ll be building, you can watch the short video intro or hit the “Live Demo” button and check it out.


Check out Live Demo for Real-Time jQuery Form Validation

Table of Contents

  1. How Will We Achieve That?
  2. Project Structure
  3. Coding the HTML
  4. Spicing It Up With CSS
  5. All The Fun: jQuery Magic
  6. Final Product
  7. After Word

How Will We Achieve That?

Now, there are actually many ways to do that; here are the most common:

  1. We could put </span> (which will be holding validation info) next to our form field and give it an ID so we can easily access its content later
  2. We could wrap every field in </p> with applied ID, and put </span> (which will be holding validation info) inside it, so we can easily access its content, through that </p>‘s child-span
  3. We could wrap every field in </p> with applied ID, and inject </span> with validation info to it

It will all work, but neither is the optimal way. Why? Because there’s too much messing with your HTML code and you’ll end up with bunch of needless tags that are required by your validation script, but which your form doesn’t really need.

It’s clearly not the way to go, so instead we’re going to do this the way I do it myself. In my opinion it’s the best solution, although it’s not very common; I honestly have never came across this method, I’ve never seen it used by someone. But if you have, please let me know in the comments.

OK, so what are we going to do?

  1. We’re going to write simplest form possible, nice and clean, no unnecessary tags whatsoever
  2. As the user fills out particular field, we’re goinng to validate it on the fly and:
    • grab its position in the window (top and left)
    • grab its width
    • add width and the left offset (from the field’s position) together so we know where the field ends
    • put validation info into </div> with applied ID, inject it to the document, position it absolutely on the spot where the field ends, and manipulate its class as needed (for example .correct or .incorrect)

That way we keep our HTML code nice and clean.

Note: It’s vital to always provide server-side validation as well (for users with turned off JavaScript).

Project Structure

We are going to need three files:

  • index.html
  • style.css
  • validation.js

I’m gonna go roughly through the HTML coding, provide you with all needed CSS – and then focus mostly on our jQuery script, which is the most important thing and what we’re hoping to learn today.

Coding the HTML

Step 1: Some Basic HTML and Importing jQuery + Validation Script

First, make index.html file and put some basic code there; you can see that we imported jQuery at the bottom, along with our validation.js file, which will contain our validation script:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Real-Time Form Validation Using jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>

<div id="content">

</div><!-- content -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="validate.js" charset="utf-8"></script>
</body>
</html>

Step 2: The Form, Splitted Into Three Sections

We’re going to split the form into three sections using </fieldset>, and </label> for each section headline:

  1. Personal Info (user name, date of birth, gender, vehicles)
  2. Email (user’s email adress)
  3. About (little info about the user)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Real-Time Form Validation Using jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>

<div id="content">
<form id="jform" action="http://1stwebdesigner.com" method="post">
	<fieldset>
		<legend>Personal Info</legend>
	</fieldset>

	<fieldset>
		<legend>Email</legend>
	</fieldset>

	<fieldset>
		<legend>About You</legend>
	</fieldset>
</form>
</div><!-- content -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="validate.js" charset="utf-8"></script>
</body>
</html>

Step 3: Adding Fields + Submit Button

Great, now it’s time to finally add some fields to our form. For this tutorial we’re going to use several different fields:

  • three text inputs: for user’s full name, date of birth and email adress
  • radio buttons for user’s gender
  • checkboxes for vehicles owned by the user
  • textarea for little info about the user
  • button for submit button

We’re going to wrap every set (label + field) in </p> to keep them separated and display them as blocks.

Your final index.html file should look like this:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Real-Time Form Validation Using jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
</head>
<body>

<div id="content">
	<form id="jform" action="http://1stwebdesigner.com" method="post">
		<fieldset>
			<legend>Personal Info</legend>
			<p>
				<label for="fullname" class="block">Full name:</label>
				<input type="text" name="fullname" id="fullname" />
			</p>
			<p>
				<label for="birthday" class="block">Day of birth <small>(dd-mm-yyyy)</small>:</label>
				<input type="text" name="birthday" id="birthday" />
			</p>
			<p>
				<label class="block">I am:</label>
				<input type="radio" name="gender" id="man" value="man" /> <label for="man">Man</label>
				<input type="radio" name="gender" id="woman" value="woman" /> <label for="woman">Woman</label>
			</p>
			<p>
				<label class="block">I own:</label>
				<input type="checkbox" name="vehicle" id="car" /> <label for="car">car</label>
				<input type="checkbox" name="vehicle" id="airplane" /> <label for="airplane">airplane</label>
				<input type="checkbox" name="vehicle" id="bicycle" /> <label for="bicycle">bicycle</label>
				<input type="checkbox" name="vehicle" id="ship" /> <label for="ship">ship</label>
			</p>
		</fieldset>

		<fieldset>
			<legend>Email</legend>
			<p>
				<label for="email" class="block">Email <small>(mickey@mou.se)</small>:</label>
				<input type="text" name="email" id="email" />
			</p>
		</fieldset>

		<fieldset>
			<legend>About You</legend>
			<p>
				<label for="about" class="block">Tell us a little bit about yourself:</label>
				<textarea id="about" cols="50" rows="10"></textarea>
			</p>
		</fieldset>
		<p>
			<button type="submit" id="send">submit</button>
		</p>
	</form>
</div><!-- content -->

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript" src="validate.js" charset="utf-8"></script>
</body>
</html>

It may look a bit messy, but it’s because of the WP’s syntax highlighting plugin. It’s actually really clean, and that’s what we wanted to achieve afterall. Check it: save the above code as your index.html file, open it in your browser and look at the source code. Now it looks clean, isn’t it?

Spicing It Up With CSS

Since CSS styling is not our main focus in this tutorial, I’m not gonna go over this, but simply provide you with the CSS you’re going to need for this to work.

Create style.css file, put inside all the code from below and that’s it! Now everything should look sweet.

body {
	background: #efefef;
	margin: 0;
	padding: 0;
	border: none;
	text-align: center;
	font: normal 13px Georgia, "Times New Roman", Times, serif;
	color: #222;
}

#content {
	width: 500px;
	margin: 0 auto;
	margin-bottom: 25px;
	padding: 0;
	text-align: left;
}

fieldset {
	margin-top: 25px;
	padding: 15px;
	border: 1px solid #d1d1d1;
	-webkit-border-radius: 7px;
	-moz-border-radius: 7px;
	border-radius: 7px;

}

fieldset legend {
	font: normal 30px Verdana, Arial, Helvetica, sans-serif;
	text-shadow: 0 1px 1px #fff;
	letter-spacing: -1px;
	color: #273953;
}

input, textarea {
	padding: 3px;
}

label {
	cursor: pointer;
}

.block {
	display: block;
}

small {
	letter-spacing: 1px;
	font-size: 11px;
	font-style: italic;
	color: #9e9e9e;
}

.info {
	text-align: left;
	padding: 5px;
	font-size: 11px;
	color: #fff;
	position: absolute;
	display: none;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
	border-radius: 5px;
	-webkit-box-shadow: -1px 1px 2px #a9a9a9;
	-moz-box-shadow: -1px 1px 2px #a9a9a9;
	box-shadow: -1px 1px 2px #a9a9a9;
}

.error {
	background: #f60000;
	border: 3px solid #d50000;

}

.correct {
	background: #56d800;
	border: 3px solid #008000;
}

.wrong {
	font-weight: bold;
	color: #e90000;
}

.normal {
	font-weight: normal;
	color: #222;
}

#send {
	background: #3f5a81;
	width: 100%;
	border: 5px solid #0F1620;
	font: bold 30px Verdana, sans-serif;
	color: #fafafa;
	text-shadow: 1px 1px 1px #0F1620;
	-webkit-border-radius: 7px;
	-moz-border-radius: 7px;
	border-radius: 7px;
}

#send:hover {
	background: #4d76b1;
	border: 5px solid #253750;
	color: #fff;
}

#send:active {
	text-indent: -10px;
}

All The Fun: jQuery Magic

This is the most interesting and engaging part. First we need to do some thinking and describe our key points.

Step 1: Planning

We have to ask ourselves three questions before we can go on:

  1. What do we need the script to do?
  2. How do we want it to do this?
  3. How do we achieve that?

It’s obvious we want the script to validate our form. But how?

  • we want to be able to validate it both in real-time (when user is filling it out) and on the form submit
  • therefore we need to make a “pack” of functions responsible for each of its fields, so we can call them:
    • individually, when the user is filling out particular field
    • all at once, on the form submit

To reduce our global footpring, we’re going to use JavaScript object for that.

Step: 2: What Do We Need?

JS object, in our case it will be:

  • jVal

Methods of that object for each of the form fields, validating that particular field:

  • jVal.fullName
  • jVal.birthDate
  • jVal.gender
  • jVal.vehicle
  • jVal.email
  • jVal.about

Variable which will hold the status of error occuring:

  • jVal.errors

And method that will be called as the last one; it will check if there were any errors and submit the form if not. If some errors occurred, it will take the user to the beginning of the form, so they can fill it out again.

  • jVal.sendIt

Now we can finally start building our validation script. When finish our first validation method, then it will be much easier and faster, as we can reuse it for other methods, only applying some changes. Let’s crack into it!

Step 3: Our Script “Packaging”

The start is really simple, almost everything will go inside this code:

$(document).ready(function(){
	jVal = {

	};
});

Step 4: Validating User’s Name

Our first method will handle user’s name. Put it inside our jVal object, like this:

var jVal = {
	'fullName' : function() {

	}
};

Now let’s put some first lines of code inside our method. Just paste it, and then I will explain what the code “says”:

$('body').append('<div id="nameInfo" class="info"></div>');

var nameInfo = $('#nameInfo');
var ele = $('#fullname');
var pos = ele.offset();
  • Line 1: We’re injecting </div> to the document. Class “info” gives it some styling (defined in our CSS file) and also make it invisible by setting display to “none” – so it’s there, but we don’t see it yet. As for the ID, it’s for easy “grabbing” and manipulating, since it will be positioned absolutely in the document. This </div> will contain our validation info that will be showed to the user, so they know if they filled out the field correctly.
  • Line 3: We’re assigning our </div> to the variable nameInfo, because we’ll be using it couple times more.
  • Line 4: We’re assigning our form field with ID “fullname” to the variable ele. The same reason as above, we will use it several times later.
  • jQuery function offset() returns current position of an element relative to the document. It returns an object containing the properties top and left. We used this function on our ele (which is actually form input with ID “fullname”), so it will return position of that element, which we assign to the variable pos.

Great, so far so good. It’s time to add some few more lines:

nameInfo.css({
	top: pos.top-3,
	left: pos.left+ele.width()+15
});
  • Line 2: We start to operate on nameInfo‘s CSS top property. Remember, our variable pos holds now the position of our form input with ID “fullname” in the document. We access its top value by simply joining pos with the word top using period . . Then we decrement that by 3 and assign it to the CSS top property of our nameInfo element.
  • Line 3: We start to operate on nameInfo‘s CSS left property. We access left value of our “Full name” input’s position, increase it by its width (we grab that from calling jQuery function width() on our ele element) and increase it by 15. The result is assigned to the CSS left property of our nameInfo element.

We’re doing really great, we just acomplished 50% of fullName, our first validating method. It’s time to actually check if the user filled our “Full name” field correctly or not, and take appropriate action:

if(ele.val().length < 6) {
	jVal.errors = true;
		nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
		ele.removeClass('normal').addClass('wrong');
} else {
		nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
		ele.removeClass('wrong').addClass('normal');
}

Lot of weird crap, huh? Don’t worry, it’s not so scary as it may look:

  • Line 1: We’re checking if the name that user typed in is shorter than 6 characters.
  • Line 2: We set our object’s variable jVal.errors to true, as we just got our first error (user’s name is too short). We’re going to use it later.
  • Line 3: We start to operate on our nameInfo element (which is the </div> we’re gonna display validation info in). First we remove the class “correct”; it may be applied to our nameInfo element from previous validation (if it was performed). Then we apply the class “error” to it. Next, we put content to our nameInfo element, it’s the information that the name should be at least 6 characters long. And finally we our alert-box visible to the user.
  • Line 4: We start to operate on our ele element (which is our form “Full name” input). First we remove class “normal”, which may be there from previous validation, then we apply class “wrong” to it.
  • Line 5: If the name user typed in was long enough, then…
  • Line 6: We start to operate on our nameInfo element. We remove class “error” if it’s there, and apply class “correct”. We put inside to let the user know it’s all good. We show the alert-box (if it wasn’t visible before).
  • Line 7: We start to operate on our ele element. We remove class “wrong” if it’s there, and apply class “normal”.

Well done! This is our first validation method. Now it’s time to test it, but before we can do that, we need to write few more lines of code.

We need to make sure, that our fullName method will be called when the user finished filling out the “Full name” field. To achieve that, we need to bind our method to certain user action. There are two great jQuery functions that would serve that purpose well: blur() and change(). We are going to use change().

Paste this code below the whole jVal object:

$('#fullname').change(jVal.fullName);

What it does in human words: if the user changes value of the “Full name” field and then leaves (e.g. to fill out another field), our fullName method is fired up, to validate “Full name” field.

Right now you should have one fully working validation method, so test it. Your whole validate.js file should like like this:

$(document).ready(function(){

	var jVal = {
		'fullName' : function() {

			$('body').append('<div id="nameInfo" class="info"></div>');

			var nameInfo = $('#nameInfo');
			var ele = $('#fullname');
			var pos = ele.offset();

			nameInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 6) {
				jVal.errors = true;
					nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		}
	};

	// bind jVal.fullName function to "Full name" form field
	$('#fullname').change(jVal.fullName);

});

Step 5: Validating User’s Date of Birth

Starting from now, it will all get easier. Our validation methods are in 90% the same, so all you have to do is copy our fullName method, and only apply some changes

Great, so now just copy whole fullName method, paste it below and rename it to birthDate. The changes we need to make are:

  • all nameInfo occurences have to become birthInfo
  • instead of #fullname, assign #birthday element to variable ele
  • add this regular expression pattern below the whole birthInfo.css() declaration:
    var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;
    
  • our previous if()statement has to become:
    if(!patt.test(ele.val()))
    
  • validation message has to become ← type in date in correct format

This is how birthDate method should look like after these changes:

	'birthDate' : function (){

		$('body').append('<div id="birthInfo" class="info"></div>');

		var birthInfo = $('#birthInfo');
		var ele = $('#birthday');
		var pos = ele.offset();

		birthInfo.css({
			top: pos.top-3,
			left: pos.left+ele.width()+15
		});

		var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;

		if(!patt.test(ele.val())) {
			jVal.errors = true;
				birthInfo.removeClass('correct').addClass('error').html('&larr; type in date in correct format').show();
				ele.removeClass('normal').addClass('wrong');
		} else {
				birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
				ele.removeClass('wrong').addClass('normal');
		}
	}
  • Line 14: It’s a regular expression pattern. It’s not our main focus in this tut, so let me just explain it very roughly. This pattern decides how the date format should look like, in this case it’s: two digits followed by hyphen then again two digits followed by hyphen and finally four digits at the end. So, the pattern applies for example to this date: 28-03-1987.
  • Line 16: We’re checking if date that user typed in conforms to our pattern from above.

And of course, we need to bind this birthDate method to the “Date of birth” form field. It’s the same thing we did with fullName before, only with different names. Paste it at the bottom (outside of the jVal object), below our fullName binding declaration:

$('#birthday').change(jVal.birthDate);

And we have another fully working validation method. Great job!

Step 6: Validating User’s Gender

Again, simply copy the whole fullName method, rename it to gender and apply these changes:

  • all nameInfo occurences have to become genderInfo
  • instead of #fullname, assign #woman element to variable ele
  • in genderInfo.css() declaration, the top value has to become top: pos.top-10 and the left value has to become left: pos.left+ele.width()+60
  • our previous if()statement has to become:
    if($('input[name="gender"]:checked').length === 0)
    
  • validation message has to become ← are you a man or a woman?

This is how gender method should look like after these changes:

'gender' : function (){

	$('body').append('<div id="genderInfo" class="info"></div>');

	var genderInfo = $('#genderInfo');
	var ele = $('#woman');
	var pos = ele.offset();

	genderInfo.css({
		top: pos.top-10,
		left: pos.left+ele.width()+60
	});

	if($('input[name="gender"]:checked').length === 0) {
		jVal.errors = true;
			genderInfo.removeClass('correct').addClass('error').html('&larr; are you a man or a woman?').show();
			ele.removeClass('normal').addClass('wrong');
	} else {
			genderInfo..removeClass('error').addClass('correct').html('&radic;').show();
			ele.removeClass('wrong').addClass('normal');
	}
}
  • Line 14: We’re checking if user selected one of two radio buttons. $('input[name="gender"]:checked') selects all inputs with name “gender” (in this case all radio buttons) that are checked. Than we check if the number of selected radios (.length) equals 0, which would mean that user didn’t select any.

As always, we have to bind this gender method to our “Gender” radio buttons:

$('input[name="gender"]').change(jVal.gender);

There, another validation method completed. Three more to go :).

Step 7: Validating Vehicles Owned by User

This time copy gender method, rename it to vehicle and apply following changes:

  • all genderInfo occurences have to become vehicleInfo
  • instead of #woman, assign #ship element to variable ele
  • in vehicleInfo.css() declaration, the left value has to become left: pos.left+ele.width()+40
  • our previous if()statement has to become:
    if($('input[name="vehicle"]:checked').length <= 1)
    
  • validation message has to become ← I am sure you have at least two!

This is how vehicle method should look like after these changes:

'vehicle' : function (){

	$('body').append('<div id="vehicleInfo" class="info"></div>');

	var vehicleInfo = $('#vehicleInfo');
	var ele = $('#ship');
	var pos = ele.offset();

	vehicleInfo.css({
		top: pos.top-10,
		left: pos.left+ele.width()+40
	});

	if($('input[name="vehicle"]:checked').length <= 1) {
		jVal.errors = true;
			vehicleInfo.removeClass('correct').addClass('error').html('&larr; I am sure you have at least two!').show();
			ele.removeClass('normal').addClass('wrong');
	} else {
			vehicleInfo.removeClass('error').addClass('correct').html('&radic;').show();
			ele.removeClass('wrong').addClass('normal');
	}
}
  • Line 14: Weíre checking if user selected two or more checkboxes. $('input[name="vehicle"]:checked') selects all inputs with name ìvehicleî (in this case all checkbox buttons) that are checked. Than we check if the number of selected checkboxes (.length method) equals or is less than 1, which would mean that user didnít select any checkboxes or selected only one.

Again, we have to bind this vehicle method to our “Vehicle” checkboxes:

$('input[name="vehicle"]').change(jVal.vehicle);

Tired? We have couple more methods to cover :). Time for email validation.

Step 8: Validating User’s Email Adress

This time, copy our birthDate method, rename it to email and apply these changes:

  • all birthInfo occurences have to become emailInfo
  • instead of #birthday, assign #email element to variable ele
  • our previous regular expression pattern has to become:
    var patt = /^.+@.+[.].{2,}$/i;
    
  • validation message has to become ← give me a valid email adress, ok?

This is how email method should look like after these changes:

	'email' : function() {

		$('body').append('<div id="emailInfo" class="info"></div>');

		var emailInfo = $('#emailInfo');
		var ele = $('#email');
		var pos = ele.offset();

		emailInfo.css({
			top: pos.top-3,
			left: pos.left+ele.width()+15
		});

		var patt = /^.+@.+[.].{2,}$/i;

		if(!patt.test(ele.val())) {
			jVal.errors = true;
				emailInfo.removeClass('correct').addClass('error').html('&larr; give me a valid email adress, ok?').show();
				ele.removeClass('normal').addClass('wrong');
		} else {
				emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
				ele.removeClass('wrong').addClass('normal');
		}
	}
  • Line 14:For this tutorial I decided to go with very simple, almost basic regular expression pattern for email adress: one or more characters followed by @ smbol, then again one or more characters followed by . period, and at the end there should be two or more characters. So, the pattern applies to this email adress example: mickey@mou.se

Of course, bind this .email method to our “Email” form field:

$('#email').change(jVal.email);

Time for the last of our validation methods: about.

Step 9: Validating User’s About Info

For this last method, copy fullName, rename it to about and apply following changes:

  • all nameInfo occurences have to become aboutInfo
  • instead of #fullname, assign #about element to variable ele
  • our previous if()statement has to become:
    if(ele.val().length < 75)
    
  • validation message has to become ← come on, tell me a little bit more!

This is how our about method should look like after these changes:

	'about' : function() {

		$('body').append('<div id="aboutInfo" class="info"></div>');

		var aboutInfo = $('#aboutInfo');
		var ele = $('#about');
		var pos = ele.offset();

		aboutInfo.css({
			top: pos.top-3,
			left: pos.left+ele.width()+15
		});

		if(ele.val().length < 75) {
			jVal.errors = true;
				aboutInfo.removeClass('correct').addClass('error').html('&larr; come on, tell me a little bit more!').show();
				ele.removeClass('normal').addClass('wrong').css({'font-weight': 'normal'});
		} else {
				aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
				ele.removeClass('wrong').addClass('normal');
		}
	}

And of course we need to bind it to our “About” form field:

$('#about').change(jVal.about);

This is it! We just completed all our validation methods. It’s almost like they say: the end is nigh! There’s only two things left to do:

  • build our last sendIt method
  • manage properly the submit action of the submit button

Step 10: Final sendIt Method

This method will be called after all our validation methods, as the last one, after clicking on the “submit” button. It will check if no errors occurred during validation (while performing any of our validation methods) up until the moment it’s called. The good news is, it couldn’t be more simple:

'sendIt' : function (){
	if(!jVal.errors) {
		$('#jform').submit();
	}
  • Line 2: Remember that errors variable I told you we’re going to use later? Well, this “later” is right now :). If even one little error occurred during the validation, this errors variable was set to true. In human words it actually means something like: “yes, it’s true that we got some errors during validation”. So here we’re checking if it’s actually NOT true, which equals to no errors from validation.
  • Line 3: If there were no errors, just finally submit the whole form.

Step 11: Managing User’s Submit Action

The only thing left now, is to manage what happens when the user clicks on our “submit” button. And it goes like this:

$('#send').click(function (){
	var obj = $.browser.webkit ? $('body') : $('html');
	obj.animate({ scrollTop: $('#jform').offset().top }, 750, function (){
		jVal.errors = false;
		jVal.fullName();
		jVal.birthDate();
		jVal.gender();
		jVal.vehicle();
		jVal.email();
		jVal.about();
		jVal.sendIt();
	});
	return false;
});
  • Line 1: We grab the send element, which is the “submit” button in our form, and if someone clicks on it we perform all code below.
  • Line 2: The thing is: when you want to apply scrolling to browser window, different browsers will work with different elements. And so: Chrome and Safari will work with body. Internet Explorer and Firefox will work with html. Opera will work with both. Unfortunately in our case we can’t just use $('html, body') to target both these elements (I’ll talk about that another time). So we need to somehow decide which of these elements we should apply scrolling to. And this is where jQuery comes with help. It provides us with $.browser property – it allows us to detect which browser we are working in. By using $.browser.webkit we’re just checking if our browser is running on webkit engine; if so then we assign body element to the obj variable we just created, if not we assign html element to it. Important note: It should be avoided and it’s considered bad practice to perform any kind of “browser detection”, you should use “feature detection” instead. But we can get away with that for our learning purposes.
  • Line 3:We apply scrollTop animation to our obj element. The point that scrolling should stop is the beginning of the form, which is determined by accessing top value of its position in the document, which we get thanks to jQueryoffset() function. Next we say that this scrolling animation should last 750 milliseconds, and when it’s done we…
  • Line 4: Set variable jVal.errors to false, to clear errors that might occurred in previous validation, and then we…
  • Lines 5-11: Call all our validation methods one by one, with sendIt method at the end, which will check if there were no errors and submit the whole form if so.
  • Line 13:We return false to that click event of the “submit” button in our form, which means that the form won’t be submitted right away, the script will perform actions planned by us first.

Final Product

Right now our validation script is fully completed and should look like this:

$(document).ready(function(){

	var jVal = {
		'fullName' : function() {

			$('body').append('<div id="nameInfo" class="info"></div>');

			var nameInfo = $('#nameInfo');
			var ele = $('#fullname');
			var pos = ele.offset();

			nameInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 6) {
				jVal.errors = true;
					nameInfo.removeClass('correct').addClass('error').html('&larr; at least 6 characters').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'birthDate' : function (){

			$('body').append('<div id="birthInfo" class="info"></div>');

			var birthInfo = $('#birthInfo');
			var ele = $('#birthday');
			var pos = ele.offset();

			birthInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			var patt = /^[0-9]{2}\-[0-9]{2}\-[0-9]{4}$/i;

			if(!patt.test(ele.val())) {
				jVal.errors = true;
					birthInfo.removeClass('correct').addClass('error').html('&larr; type in date in correct format').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					birthInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'gender' : function (){

			$('body').append('<div id="genderInfo" class="info"></div>');

			var genderInfo = $('#genderInfo');
			var ele = $('#woman');
			var pos = ele.offset();

			genderInfo.css({
				top: pos.top-10,
				left: pos.left+ele.width()+60
			});

			if($('input[name="gender"]:checked').length === 0) {
				jVal.errors = true;
					genderInfo.removeClass('correct').addClass('error').html('&larr; are you a man or a woman?').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					genderInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'vehicle' : function (){

			$('body').append('<div id="vehicleInfo" class="info"></div>');

			var vehicleInfo = $('#vehicleInfo');
			var ele = $('#ship');
			var pos = ele.offset();

			vehicleInfo.css({
				top: pos.top-10,
				left: pos.left+ele.width()+40
			});

			if($('input[name="vehicle"]:checked').length <= 1) {
				jVal.errors = true;
					vehicleInfo.removeClass('correct').addClass('error').html('&larr; I\'m sure you have at least two!').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					vehicleInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'email' : function() {

			$('body').append('<div id="emailInfo" class="info"></div>');

			var emailInfo = $('#emailInfo');
			var ele = $('#email');
			var pos = ele.offset();

			emailInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			var patt = /^.+@.+[.].{2,}$/i;

			if(!patt.test(ele.val())) {
				jVal.errors = true;
					emailInfo.removeClass('correct').addClass('error').html('&larr; give me a valid email adress, ok?').show();
					ele.removeClass('normal').addClass('wrong');
			} else {
					emailInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'about' : function() {

			$('body').append('<div id="aboutInfo" class="info"></div>');

			var aboutInfo = $('#aboutInfo');
			var ele = $('#about');
			var pos = ele.offset();

			aboutInfo.css({
				top: pos.top-3,
				left: pos.left+ele.width()+15
			});

			if(ele.val().length < 75) {
				jVal.errors = true;
					aboutInfo.removeClass('correct').addClass('error').html('&larr; come on, tell me a little bit more!').show();
					ele.removeClass('normal').addClass('wrong').css({'font-weight': 'normal'});
			} else {
					aboutInfo.removeClass('error').addClass('correct').html('&radic;').show();
					ele.removeClass('wrong').addClass('normal');
			}
		},

		'sendIt' : function (){
			if(!jVal.errors) {
				$('#jform').submit();
			}
		}
	};

// ====================================================== //

	$('#send').click(function (){
		var obj = $.browser.webkit ? $('body') : $('html');
		obj.animate({ scrollTop: $('#jform').offset().top }, 750, function (){
			jVal.errors = false;
			jVal.fullName();
			jVal.birthDate();
			jVal.gender();
			jVal.vehicle();
			jVal.email();
			jVal.about();
			jVal.sendIt();
		});
		return false;
	});

	$('#fullname').change(jVal.fullName);
	$('#birthday').change(jVal.birthDate);
	$('input[name="gender"]').change(jVal.gender);
	$('input[name="vehicle"]').change(jVal.vehicle);
	$('#email').change(jVal.email);
	$('#about').change(jVal.about);

});
Check out Live Demo for Real-Time jQuery Form Validation

After Word

We’ve done it. Well, you have done it! I hope you enjoyed this tutorial and learned something. If you have any questions feel free to ask; I will be glad to talk more in the comments. Thanks for your time!

3 Written ArticlesWebsite

Web developer and designer, pure breed JavaScript nut. Have unstoppable and never-ending need of learning. Literally inhaling books. You can follow him on Twitter if you'd like, or check out what he's working on on Dribbble.

69 Comments Best Comments First
  • Anand

    Friday, November 4th, 2011 09:08

    50

    Hi What if the form has two address fields and I need to validate two address fields with same validation .
    In the method that you have created it is validating the field based on its Id (statically),
    how can this be changed to dynamic so that any number of fields in the form with same validation can be validated.
    This would be great help if you can figure it out.

    Thank you for sharing such a nice article.

    +2
  • fahmi

    Saturday, October 8th, 2011 09:55

    47

    Hi sir, will you help me if you don’t mind. I wanna achieve validation something like this website does.

    You can see that the validation sits in a fixed place and the border of wrong field changes color. I’m sorry but I have to say that I got no experience with jQuery nor Javascript.

    Hope you can help thanks.

    +1
  • BBN

    Tuesday, August 23rd, 2011 21:56

    45

    thanks. it was very useful.

    +1
  • Astrid

    Wednesday, May 19th, 2010 15:58

    24

    Great tutorial!
    Everything is working fine with me until I use php to send the contact form to an email adress. Could somebody help me?
    My form is send to:

    The form.php sends the form to an email adress. But something goes wrong in combination with the validation of jquery.
    I know it has got something to do with:
    $(‘#send’).click(function (){
    var obj = $.browser.webkit ? $(‘body’) : $(‘html’);
    obj.animate({ scrollTop: $(‘#jform’).offset().top }, 750, function (){
    jVal.errors = false;
    jVal.fullName();
    jVal.birthDate();
    jVal.gender();
    jVal.vehicle();
    jVal.email();
    jVal.about();
    jVal.sendIt();
    });
    return false;
    });

    If I remove ‘return false’, the form is send to the email adress but of course the validation does not work the way it has to do.
    I am kind of a newbie at Javascript so I cant figure it out…

    +1
  • Sajid Ali

    Friday, November 11th, 2011 16:21

    51

    Really really this is very very informative and useful article i really appreciate it

    very thank you dear please keep it up

    +1
  • Ryan Turki

    Tuesday, May 4th, 2010 11:44

    7

    Great tut Michal ! Thanks

    0
  • KLM

    Thursday, May 13th, 2010 21:59

    23

    How would the function look without the scroll object?

    0
  • Weblapkészítés

    Thursday, May 13th, 2010 15:33

    22

    Hi Kozak!

    Yess, this post is a great work, I understood it from zero javascript knowledge!

    Best regards!

    0
  • Jared Detroit

    Monday, May 3rd, 2010 20:05

    3

    This is great! I’ve been telling myself I need to learn more jquery and this is a perfect example of not only what I need for my website but how to actually do it. Thanks for the complete example!

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:05

      11

      Glad I could help :). Just remember that this is just an example. It can be done much better, and of course has to be tweaked to your needs.

      0
  • Carli

    Monday, May 3rd, 2010 13:30

    2

    Well the date validation is a bit bugy, date format is like dd-mm-yyyy, and if I enter 15-15-2010, the date is valid, but we all know that there is only 12 months in one year. ;) In LIVE example …

    0
    • Michal Kozak

      Monday, May 3rd, 2010 19:07

      5

      Yup :), it just checks if the format is correct, nothing more (so like 2digits-2digits-4digits).

      This is just an example, remember :). There’s a room for improvement, changes and rewriting, can be done in many different ways, like with everything.

      It should be treated like something you can build your own validation upon, nothing more.

      0
      • BBoy

        Friday, June 10th, 2011 23:22

        39

        Hi!

        cool tutorial!
        I still have one question, if you find the time to answer it.
        I was looking all around google but I couldn’t find how to change the date format from dd-mm-yyyy to just yyyy.

        i tried like this:
        /^[1-2][0-9][0-9][0-9]}$/;
        and
        /^[0-9]{4}$/i;

        but none worked. Maybe someone knows why.
        Thank for your time and for the nice tut!

        cheers!

        0
  • jhon

    Thursday, May 20th, 2010 09:55

    25

    Is there anyway to validate dynamic generated element?

    0
  • seyon

    Wednesday, August 4th, 2010 00:59

    30

    Hi,
    I have a problem. This script is not working from my server at all. I couldn’t figure what went wrong. I have put all the files in the follwing directory without any modification. You can see that it is going to target page without doing any validation.
    http://www.nilavoip.com/forms/form.html
    Any help would be much appreciated.
    Thanks.
    -Seyon.

    0
  • Benny

    Thursday, August 5th, 2010 16:26

    31

    Hi,

    very nice addon. I have a question. I use your validation and the addon “http://jqueryui.com/demos/datepicker/”

    When I not filled in the date input field and submit the form I got the message “Please fill in your date”. Very nice. But when I click the date input field choose a date I have a javascript where focus the next field

    $(document).ready(function() {
    $(“#datepicker”).datepicker({
    onSelect: function(dateText, inst) {
    document.forms[0].ort.focus()
    }
    });
    });

    but the message “Please fill in your date” don´t disappear. What can I do, does the field disappear.
    When you need more information tell me.

    Thanks for your help.

    Regards
    Benny

    0
  • Abhishek

    Sunday, July 11th, 2010 06:50

    29

    Maybe you could have provided a link to download the finished files!

    0
  • Velizar

    Tuesday, June 22nd, 2010 22:39

    28

    I am very new to jquery. This article is excellent and it helped me in more ways than I expected as I’ve been pondering over a problem of mine for a day or so. For a .NET developer like me stuck with a single form on a page this method allows the flexibility to validate certain fields and ignore others until you need to validate them. I had a problem with a page which updated a couple of db fields but jquery validate would look at the entire form even though the fields were initially hidden. Your way allowed me to assign validation to the button click event of the dialog ( called from an .aspx page, using a master page, an update panel, and the button is inside a grid) and prevent a postback if validation is invalid. So thank you for this :)

    I don’t want to litter your blog so anyone with the same problem – happy to share the code, let me know dimitrov.velizar@gmail.com

    0
  • Sandeep Malik

    Friday, June 11th, 2010 19:29

    26

    good sir, its too help full.

    0
  • Theo

    Monday, June 14th, 2010 12:52

    27

    Great tutorial, very well written. Thanks !

    0
  • Gian

    Wednesday, May 12th, 2010 16:54

    20

    Hey, nice this plugin, but I think that is a little bug with date validation.

    I tried 22-13-2020 and I got OK with month 13

    hug

    0
  • KLM

    Tuesday, May 4th, 2010 18:37

    8

    If I set a form field to display:none how do I get the validation to ignore those fields?

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:04

      10

      Simply don’t apply any validation to the that particular field :).

      0
      • KLM

        Tuesday, May 4th, 2010 22:13

        9

        Hi Michael, thanks for this awesome validation. Sometimes the field is required if it’s displayed and not if it’s hidden. I’m might have to create multiple validation scripts to call when needed.

        0
  • Michal Kozak

    Tuesday, May 4th, 2010 22:11

    14

    Thank you all very much for kind word :).

    As long as we’re on taht topic – I’m currently developing new, standalone JavaScript library, fully dedicated to form validation. It aims to provide very easy, simple, and highly customizable validation. I hope it will be released this year :).

    0
  • Michal Kozak

    Wednesday, May 5th, 2010 15:59

    15

    Not at all, glad it’s helpful.

    0
  • Ron

    Tuesday, September 7th, 2010 04:18

    32

    Hi, I loved your tutorial and especially the video beforehand. I copied your exact source code (three different times) from the three files (css, js, html) and placed them on two different servers. Unfortunately, the code did not work on either. The form looks perfectly the same as yours, but validation is not taking place and no errors are being shown. I used the source code copy button on each type of file and have verified that they are the same.

    Any ideas on what I could be doing wrong?

    Thanks

    Ron

    0
  • joddy street

    Tuesday, May 4th, 2010 08:13

    6

    this is so far the best tute i have read about jquery form validation. loved the effect

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:08

      13

      Thank you, I appreciate it a lot. Hope to give you some new stuff, soon.

      0
  • Michal Kozak

    Tuesday, May 11th, 2010 05:08

    19

    Thanks a lot, I’m glad you liked it :).

    0
  • masaru edo

    Monday, May 10th, 2010 11:41

    18

    I like this tutorial. Great… banget lah :)

    0
  • KLM

    Thursday, May 6th, 2010 08:02

    16

    Is there a way to set up the system to validate if the id exists only, if the id does not exist skip the validation function for that id? My form is dynamic and on the first init of it it shows all fields with all validation id’s, on the second load, some id’s are removed to prevent the user from changing their entries and does not require the validation.

    if id exists – call validation function, if id is null skip validation function

    Great script, so close to getting it perfect for what I need.

    Thanks Michal!

    0
    • Michal Kozak

      Thursday, May 6th, 2010 12:30

      17

      Yeah, but you need something additional.

      Since you first have to GRAB that particular element/field to check if you should validate it or not.

      So basically you need to have that ID in case to easily grab this element, but you can still achieve what you want.

      Leave ID alone, but you can add a CLASS to that field, it can be:

      class=”validate”

      And then you could do something like:

      if ($(‘#yourElement’).hasClass(‘validate’)) {
      // validation script goes here
      }

      It can be done in many different ways – thing is, you have to plan it before you start building it. I didn’t need something like you do, so I didn’t optimize script for that.

      But you can use the method above, it will work just fine. You just have to figure something out with your IDs. For example: why do you remove them? Instead of removing the field, you can leave them and make them:

      disabled=”disabled”

      That way user won’t get to change it anymore, but the filed will still be there. Let me know how it worked out, cheers.

      0
      • KLM

        Thursday, May 13th, 2010 00:29

        21

        Michal, this is working really well. I am stuck on one thing, I am trying to incorporate the following CC luhn javascript and can’t seem to get it to work. How do I check the the value is = 0; i -= 2) {
        sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
        }
        for (i = cc.length – 1; i >= 0; i -= 2) {
        sum += parseInt (cc.charAt (i), 10);
        }
        return (sum % 10) == 0;
        }

        0
  • SimonJPA

    Friday, March 11th, 2011 22:51

    35

    Hi,

    Great work!

    I using your code to do a contact form on a new project I’m working on.

    I did make some changes. I have a problem.

    I did put a combo box on the form and when you send the form, the validation error goes on the top of the left corner.

    Here’s the code of the combo and the validation code:

    Subject:

    Choose
    1
    2
    3
    4
    Other

    ‘subject’ : function (){

    $(‘body’).append(”);

    var subjectInfo = $(‘#subjectInfo’);
    var ele = $(‘#subject’);
    var pos = ele.offset();

    subjectInfo.css({
    top: pos.top-3,
    left: pos.left+ele.width()+15
    });

    if($(‘option[id="subject"]:selected’).length === 0) {
    jVal.errors = true;
    subjectInfo.removeClass(‘correct’).addClass(‘error’).html(‘← subject?’).show();
    ele.removeClass(‘normal’).addClass(‘wrong’);
    } else {
    subjectInfo.removeClass(‘error’).addClass(‘correct’).html(‘√’).show();
    ele.removeClass(‘wrong’).addClass(‘normal’);
    }
    },

    Regards

    0
    • venkatsh

      Sunday, September 11th, 2011 21:18

      46

      I am ui developer ( css,XHTML,jquery) & Designing ( adobe photoshop, corldrow,Indesign creating templates & logos ext….)
      I haveing 4years of exp

      0
  • Jade

    Wednesday, September 8th, 2010 10:21

    33

    Hello, I was wondering how you would go about making the jQuery check for a certain number in a field, and validating that.

    Say if you wanted the value to be 1 – 50, but not over 50.
    I thought of using the var patt = /^[0-5][0-9]$/;
    But that brings the problem of allowing 51-59.

    Thanks for the tutorial =)

    0
  • gopi

    Friday, December 9th, 2011 12:43

    60

    hi
    i’m new to jquery…can you give me a code to validate a text box using jquery…

    0
  • Martin

    Thursday, December 22nd, 2011 11:01

    61

    Hi, its a good job. God bless you.

    0
  • Muhammad Hamza Asif

    Thursday, December 8th, 2011 17:31

    59

    Thanks For This Awesome Tutorial. I am UI DEVELOPEr and this help me alot

    0
  • Muhammad Hamza Asif

    Thursday, December 8th, 2011 17:30

    58

    Thankx For This tutorial. I was looking for it from so long. And this Jquery Form Validation really help me alot. I would in future keep following your website for such a nice HTML and JQUERY tips and tricks

    0
  • Helen

    Wednesday, November 23rd, 2011 12:31

    57

    Thank you for a great and detailed tutorial.
    I’m just curious about the $(‘html, body’).animate and the fact that you wrote “I’ll talk about that another time”.
    As you described that is not the correct way to code. And i’m all about coding the correct way.
    I can’t sleep at night…
    Would you please elaborate?

    0
  • Harold

    Friday, December 30th, 2011 23:35

    62

    Hi was wondering if I could use the above jquery validation code on my website. I will address you as the author of the code.

    0
  • Jams

    Friday, January 6th, 2012 07:03

    63

    Wow this tutorial is really amazing, certainly you take your time to explain all the details, thank you so much for sharing it!.

    0
  • Tommy

    Thursday, March 8th, 2012 22:53

    68

    Great tutorial, helped me a lot!

    It works perfectly on my server but I have a question about the code:

    You bound the fullname input field to run jVal.fullname everytime it changes and in the jVal.fullname function you create a new div tag everytime. Does this mean that everytime the user edits the fullname field, a new div is created on top of the old one?

    0
  • Brad Givens

    Friday, March 9th, 2012 15:59

    69

    Hi there,
    I found that the regex for the email doesn’t allow for a period in the username, i.e. first.last@acme.com. How could I allow for that?

    GREAT post btw!

    0
  • Celestino Veiga

    Monday, February 27th, 2012 15:11

    67

    Hello,

    The tutorial and script on Real-Time Form Validation Using jQuery are interesting. I tried it and found two problems:
    1 – if the name of input field has only one word, example “input id=u” it this field is not validated, that is, no message is displayed by the script..

    2 – if the input field is of type password, also this field is not validated, that is, no message is displayed by the script

    Any help?

    0
  • Shaun stewart

    Monday, February 20th, 2012 21:43

    66

    I am having trouble getting the jquery to recognize the name of the text box if the asp.net page has a Master page. the ID and the name are different.

    0
  • sanjayr

    Friday, January 6th, 2012 10:08

    64

    Hi

    I would like to add password & re-enter password fields, where the re-entered password should be same as that of password. How to do that with jVal. Can someone please help me on that…..?

    0
  • John

    Monday, February 6th, 2012 21:18

    65

    Sir, thank you for sharing this.
    This has been very helpful !

    0
  • Aron

    Sunday, November 20th, 2011 16:52

    55

    /* */

    what this stand for? what is it’s function?

    0
    • Rean John Uehara

      Monday, November 21st, 2011 04:10

      56

      It’s used to insert comments in between codes.

      0
  • ovi

    Saturday, November 19th, 2011 10:02

    54

    how do you use Ajax, for checking username whether available or not from database ? please help me ? When I add like below in userName:function (), I got error no response from ajax.

    if(ele.val().length < 3) {
    jVal.errors = true;
    usernameInfo.removeClass('correct').addClass('error').html('← Isikan Username untuk Anda minimal 3 huruf').show();
    ele.removeClass('normal').addClass('wrong');
    } else {

    // var user_name = ele.val();

    jQuery.ajax({
    type: "POST",
    url: "checkusername.php",
    data: 'user_name='+ ele.val(),
    cache: false,
    success: function(response){
    if(response == 1){
    jVal.errors = true;
    usernameInfo.removeClass('correct').addClass('error').html('← Username sudah ada yg memiliki. Isi dengan username yang lain').show();
    ele.removeClass('normal').addClass('wrong');

    }else {
    usernameInfo.removeClass('error').addClass('correct').html('√').show();
    ele.removeClass('wrong').addClass('normal');
    }
    }
    });

    0
  • mDobbs

    Wednesday, June 1st, 2011 04:20

    38

    Hi,
    Is there a part 2 to this example as I’m having trouble on how to send the form using php?

    Any help would be great thanks

    0
  • Naga Bhanu

    Tuesday, April 26th, 2011 14:39

    37

    In this page there is no alignment.

    0
  • Kentaro Ann Arbor

    Thursday, April 21st, 2011 08:38

    36

    I don’t do much javascript work but this was very easy to understand. Thanks!

    0
  • Brett Widmann

    Thursday, October 28th, 2010 00:14

    34

    This has been very helpful. Thanks for sharing. Works great.

    0
  • Keiron Lowe

    Monday, May 3rd, 2010 13:48

    1

    Fantastic Tutorial, I love this website :D
    I’m assuming this doesnt send the email, this is just the validation?

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:07

      12

      In the example, it sends the data you put into form field, but that data is not processed in any way :). It actually sends it to 1stwebdesigner’s home page, where it’s just NOT taken care of :).

      0
    • Michal Kozak

      Monday, May 3rd, 2010 19:04

      4

      Thanks a lot :).

      0
  • Maverick

    Sunday, June 12th, 2011 01:57

    40

    Thank you so much for this great tutorial !!
    Studied google such a long time but your stuff is the best understanding I’ve seen.

    Thanks!!!!

    0
  • GB

    Monday, June 27th, 2011 13:14

    41

    It’s really great that you put the time to explain all this with so much care and detail. It makes it really useful for people who don’t have tons of web experience. Thank you.

    0
  • Scott

    Tuesday, November 15th, 2011 04:36

    52

    Thanks! you rock

    0
  • Vidya

    Thursday, November 17th, 2011 10:31

    53

    Hi,
    I am a newbie and the tutorial really helped me .
    You are great……..Thank you very much

    0
  • Will

    Thursday, July 21st, 2011 02:42

    42

    Thank you for taking the time to build this tutorial, I really appreciate the great work you did. Having a hands-on experience like this really jump-started my jQuery comprehension!

    0
  • AustinTxous

    Monday, October 17th, 2011 18:54

    48

    Great work! Thanks for the detailed explanations.
    I added 1 line at the beginning of the code so the cursor is automatically placed in the first field when page opens. You can put this just INSIDE the document.ready function:

    document.forms['jform'].elements['fullname'].focus();

    -1
    • Joby Joseph

      Thursday, October 20th, 2011 03:18

      49

      OMG. What a tutorial! you are great. spending time for each and every detail. Your patience is much appreciated. you should write more..

      +3
  • Shailesh

    Monday, August 22nd, 2011 13:55

    44

    will you please tell me how this can be integrated when i have more than one form tags inside a web page

    -1
  • Kalpesh

    Wednesday, August 10th, 2011 19:45

    43

    sir,
    its very simple code and its run properly but the problem is that i want to submit a form using php instead of jquery form submit method but it dosent work. here is the same procedure look like JavaScript? i mean when the condition is false then “return false” and executing stopped or when condition is true then “return true” and then means it will com into the .php file and run code.
    here JQuery code where i put the return true so that .php file’s executing continue.

    -1
  • Brad Givens

    Friday, March 9th, 2012 15:59

    69

    Hi there,
    I found that the regex for the email doesn’t allow for a period in the username, i.e. first.last@acme.com. How could I allow for that?

    GREAT post btw!

    0
  • Tommy

    Thursday, March 8th, 2012 22:53

    68

    Great tutorial, helped me a lot!

    It works perfectly on my server but I have a question about the code:

    You bound the fullname input field to run jVal.fullname everytime it changes and in the jVal.fullname function you create a new div tag everytime. Does this mean that everytime the user edits the fullname field, a new div is created on top of the old one?

    0
  • Celestino Veiga

    Monday, February 27th, 2012 15:11

    67

    Hello,

    The tutorial and script on Real-Time Form Validation Using jQuery are interesting. I tried it and found two problems:
    1 – if the name of input field has only one word, example “input id=u” it this field is not validated, that is, no message is displayed by the script..

    2 – if the input field is of type password, also this field is not validated, that is, no message is displayed by the script

    Any help?

    0
  • Shaun stewart

    Monday, February 20th, 2012 21:43

    66

    I am having trouble getting the jquery to recognize the name of the text box if the asp.net page has a Master page. the ID and the name are different.

    0
  • John

    Monday, February 6th, 2012 21:18

    65

    Sir, thank you for sharing this.
    This has been very helpful !

    0
  • sanjayr

    Friday, January 6th, 2012 10:08

    64

    Hi

    I would like to add password & re-enter password fields, where the re-entered password should be same as that of password. How to do that with jVal. Can someone please help me on that…..?

    0
  • Jams

    Friday, January 6th, 2012 07:03

    63

    Wow this tutorial is really amazing, certainly you take your time to explain all the details, thank you so much for sharing it!.

    0
  • Harold

    Friday, December 30th, 2011 23:35

    62

    Hi was wondering if I could use the above jquery validation code on my website. I will address you as the author of the code.

    0
  • Martin

    Thursday, December 22nd, 2011 11:01

    61

    Hi, its a good job. God bless you.

    0
  • gopi

    Friday, December 9th, 2011 12:43

    60

    hi
    i’m new to jquery…can you give me a code to validate a text box using jquery…

    0
  • Muhammad Hamza Asif

    Thursday, December 8th, 2011 17:31

    59

    Thanks For This Awesome Tutorial. I am UI DEVELOPEr and this help me alot

    0
  • Muhammad Hamza Asif

    Thursday, December 8th, 2011 17:30

    58

    Thankx For This tutorial. I was looking for it from so long. And this Jquery Form Validation really help me alot. I would in future keep following your website for such a nice HTML and JQUERY tips and tricks

    0
  • Helen

    Wednesday, November 23rd, 2011 12:31

    57

    Thank you for a great and detailed tutorial.
    I’m just curious about the $(‘html, body’).animate and the fact that you wrote “I’ll talk about that another time”.
    As you described that is not the correct way to code. And i’m all about coding the correct way.
    I can’t sleep at night…
    Would you please elaborate?

    0
  • Aron

    Sunday, November 20th, 2011 16:52

    55

    /* */

    what this stand for? what is it’s function?

    0
    • Rean John Uehara

      Monday, November 21st, 2011 04:10

      56

      It’s used to insert comments in between codes.

      0
  • ovi

    Saturday, November 19th, 2011 10:02

    54

    how do you use Ajax, for checking username whether available or not from database ? please help me ? When I add like below in userName:function (), I got error no response from ajax.

    if(ele.val().length < 3) {
    jVal.errors = true;
    usernameInfo.removeClass('correct').addClass('error').html('← Isikan Username untuk Anda minimal 3 huruf').show();
    ele.removeClass('normal').addClass('wrong');
    } else {

    // var user_name = ele.val();

    jQuery.ajax({
    type: "POST",
    url: "checkusername.php",
    data: 'user_name='+ ele.val(),
    cache: false,
    success: function(response){
    if(response == 1){
    jVal.errors = true;
    usernameInfo.removeClass('correct').addClass('error').html('← Username sudah ada yg memiliki. Isi dengan username yang lain').show();
    ele.removeClass('normal').addClass('wrong');

    }else {
    usernameInfo.removeClass('error').addClass('correct').html('√').show();
    ele.removeClass('wrong').addClass('normal');
    }
    }
    });

    0
  • Vidya

    Thursday, November 17th, 2011 10:31

    53

    Hi,
    I am a newbie and the tutorial really helped me .
    You are great……..Thank you very much

    0
  • Scott

    Tuesday, November 15th, 2011 04:36

    52

    Thanks! you rock

    0
  • Sajid Ali

    Friday, November 11th, 2011 16:21

    51

    Really really this is very very informative and useful article i really appreciate it

    very thank you dear please keep it up

    +1
  • Anand

    Friday, November 4th, 2011 09:08

    50

    Hi What if the form has two address fields and I need to validate two address fields with same validation .
    In the method that you have created it is validating the field based on its Id (statically),
    how can this be changed to dynamic so that any number of fields in the form with same validation can be validated.
    This would be great help if you can figure it out.

    Thank you for sharing such a nice article.

    +2
  • AustinTxous

    Monday, October 17th, 2011 18:54

    48

    Great work! Thanks for the detailed explanations.
    I added 1 line at the beginning of the code so the cursor is automatically placed in the first field when page opens. You can put this just INSIDE the document.ready function:

    document.forms['jform'].elements['fullname'].focus();

    -1
    • Joby Joseph

      Thursday, October 20th, 2011 03:18

      49

      OMG. What a tutorial! you are great. spending time for each and every detail. Your patience is much appreciated. you should write more..

      +3
  • fahmi

    Saturday, October 8th, 2011 09:55

    47

    Hi sir, will you help me if you don’t mind. I wanna achieve validation something like this website does.

    You can see that the validation sits in a fixed place and the border of wrong field changes color. I’m sorry but I have to say that I got no experience with jQuery nor Javascript.

    Hope you can help thanks.

    +1
  • BBN

    Tuesday, August 23rd, 2011 21:56

    45

    thanks. it was very useful.

    +1
  • Shailesh

    Monday, August 22nd, 2011 13:55

    44

    will you please tell me how this can be integrated when i have more than one form tags inside a web page

    -1
  • Kalpesh

    Wednesday, August 10th, 2011 19:45

    43

    sir,
    its very simple code and its run properly but the problem is that i want to submit a form using php instead of jquery form submit method but it dosent work. here is the same procedure look like JavaScript? i mean when the condition is false then “return false” and executing stopped or when condition is true then “return true” and then means it will com into the .php file and run code.
    here JQuery code where i put the return true so that .php file’s executing continue.

    -1
  • Will

    Thursday, July 21st, 2011 02:42

    42

    Thank you for taking the time to build this tutorial, I really appreciate the great work you did. Having a hands-on experience like this really jump-started my jQuery comprehension!

    0
  • GB

    Monday, June 27th, 2011 13:14

    41

    It’s really great that you put the time to explain all this with so much care and detail. It makes it really useful for people who don’t have tons of web experience. Thank you.

    0
  • Maverick

    Sunday, June 12th, 2011 01:57

    40

    Thank you so much for this great tutorial !!
    Studied google such a long time but your stuff is the best understanding I’ve seen.

    Thanks!!!!

    0
  • mDobbs

    Wednesday, June 1st, 2011 04:20

    38

    Hi,
    Is there a part 2 to this example as I’m having trouble on how to send the form using php?

    Any help would be great thanks

    0
  • Naga Bhanu

    Tuesday, April 26th, 2011 14:39

    37

    In this page there is no alignment.

    0
  • Kentaro Ann Arbor

    Thursday, April 21st, 2011 08:38

    36

    I don’t do much javascript work but this was very easy to understand. Thanks!

    0
  • SimonJPA

    Friday, March 11th, 2011 22:51

    35

    Hi,

    Great work!

    I using your code to do a contact form on a new project I’m working on.

    I did make some changes. I have a problem.

    I did put a combo box on the form and when you send the form, the validation error goes on the top of the left corner.

    Here’s the code of the combo and the validation code:

    Subject:

    Choose
    1
    2
    3
    4
    Other

    ‘subject’ : function (){

    $(‘body’).append(”);

    var subjectInfo = $(‘#subjectInfo’);
    var ele = $(‘#subject’);
    var pos = ele.offset();

    subjectInfo.css({
    top: pos.top-3,
    left: pos.left+ele.width()+15
    });

    if($(‘option[id="subject"]:selected’).length === 0) {
    jVal.errors = true;
    subjectInfo.removeClass(‘correct’).addClass(‘error’).html(‘← subject?’).show();
    ele.removeClass(‘normal’).addClass(‘wrong’);
    } else {
    subjectInfo.removeClass(‘error’).addClass(‘correct’).html(‘√’).show();
    ele.removeClass(‘wrong’).addClass(‘normal’);
    }
    },

    Regards

    0
    • venkatsh

      Sunday, September 11th, 2011 21:18

      46

      I am ui developer ( css,XHTML,jquery) & Designing ( adobe photoshop, corldrow,Indesign creating templates & logos ext….)
      I haveing 4years of exp

      0
  • Brett Widmann

    Thursday, October 28th, 2010 00:14

    34

    This has been very helpful. Thanks for sharing. Works great.

    0
  • Jade

    Wednesday, September 8th, 2010 10:21

    33

    Hello, I was wondering how you would go about making the jQuery check for a certain number in a field, and validating that.

    Say if you wanted the value to be 1 – 50, but not over 50.
    I thought of using the var patt = /^[0-5][0-9]$/;
    But that brings the problem of allowing 51-59.

    Thanks for the tutorial =)

    0
  • Ron

    Tuesday, September 7th, 2010 04:18

    32

    Hi, I loved your tutorial and especially the video beforehand. I copied your exact source code (three different times) from the three files (css, js, html) and placed them on two different servers. Unfortunately, the code did not work on either. The form looks perfectly the same as yours, but validation is not taking place and no errors are being shown. I used the source code copy button on each type of file and have verified that they are the same.

    Any ideas on what I could be doing wrong?

    Thanks

    Ron

    0
  • Benny

    Thursday, August 5th, 2010 16:26

    31

    Hi,

    very nice addon. I have a question. I use your validation and the addon “http://jqueryui.com/demos/datepicker/”

    When I not filled in the date input field and submit the form I got the message “Please fill in your date”. Very nice. But when I click the date input field choose a date I have a javascript where focus the next field

    $(document).ready(function() {
    $(“#datepicker”).datepicker({
    onSelect: function(dateText, inst) {
    document.forms[0].ort.focus()
    }
    });
    });

    but the message “Please fill in your date” don´t disappear. What can I do, does the field disappear.
    When you need more information tell me.

    Thanks for your help.

    Regards
    Benny

    0
  • seyon

    Wednesday, August 4th, 2010 00:59

    30

    Hi,
    I have a problem. This script is not working from my server at all. I couldn’t figure what went wrong. I have put all the files in the follwing directory without any modification. You can see that it is going to target page without doing any validation.
    http://www.nilavoip.com/forms/form.html
    Any help would be much appreciated.
    Thanks.
    -Seyon.

    0
  • Abhishek

    Sunday, July 11th, 2010 06:50

    29

    Maybe you could have provided a link to download the finished files!

    0
  • Velizar

    Tuesday, June 22nd, 2010 22:39

    28

    I am very new to jquery. This article is excellent and it helped me in more ways than I expected as I’ve been pondering over a problem of mine for a day or so. For a .NET developer like me stuck with a single form on a page this method allows the flexibility to validate certain fields and ignore others until you need to validate them. I had a problem with a page which updated a couple of db fields but jquery validate would look at the entire form even though the fields were initially hidden. Your way allowed me to assign validation to the button click event of the dialog ( called from an .aspx page, using a master page, an update panel, and the button is inside a grid) and prevent a postback if validation is invalid. So thank you for this :)

    I don’t want to litter your blog so anyone with the same problem – happy to share the code, let me know dimitrov.velizar@gmail.com

    0
  • Theo

    Monday, June 14th, 2010 12:52

    27

    Great tutorial, very well written. Thanks !

    0
  • Sandeep Malik

    Friday, June 11th, 2010 19:29

    26

    good sir, its too help full.

    0
  • jhon

    Thursday, May 20th, 2010 09:55

    25

    Is there anyway to validate dynamic generated element?

    0
  • Astrid

    Wednesday, May 19th, 2010 15:58

    24

    Great tutorial!
    Everything is working fine with me until I use php to send the contact form to an email adress. Could somebody help me?
    My form is send to:

    The form.php sends the form to an email adress. But something goes wrong in combination with the validation of jquery.
    I know it has got something to do with:
    $(‘#send’).click(function (){
    var obj = $.browser.webkit ? $(‘body’) : $(‘html’);
    obj.animate({ scrollTop: $(‘#jform’).offset().top }, 750, function (){
    jVal.errors = false;
    jVal.fullName();
    jVal.birthDate();
    jVal.gender();
    jVal.vehicle();
    jVal.email();
    jVal.about();
    jVal.sendIt();
    });
    return false;
    });

    If I remove ‘return false’, the form is send to the email adress but of course the validation does not work the way it has to do.
    I am kind of a newbie at Javascript so I cant figure it out…

    +1
  • KLM

    Thursday, May 13th, 2010 21:59

    23

    How would the function look without the scroll object?

    0
  • Weblapkészítés

    Thursday, May 13th, 2010 15:33

    22

    Hi Kozak!

    Yess, this post is a great work, I understood it from zero javascript knowledge!

    Best regards!

    0
  • Gian

    Wednesday, May 12th, 2010 16:54

    20

    Hey, nice this plugin, but I think that is a little bug with date validation.

    I tried 22-13-2020 and I got OK with month 13

    hug

    0
  • Michal Kozak

    Tuesday, May 11th, 2010 05:08

    19

    Thanks a lot, I’m glad you liked it :).

    0
  • masaru edo

    Monday, May 10th, 2010 11:41

    18

    I like this tutorial. Great… banget lah :)

    0
  • KLM

    Thursday, May 6th, 2010 08:02

    16

    Is there a way to set up the system to validate if the id exists only, if the id does not exist skip the validation function for that id? My form is dynamic and on the first init of it it shows all fields with all validation id’s, on the second load, some id’s are removed to prevent the user from changing their entries and does not require the validation.

    if id exists – call validation function, if id is null skip validation function

    Great script, so close to getting it perfect for what I need.

    Thanks Michal!

    0
    • Michal Kozak

      Thursday, May 6th, 2010 12:30

      17

      Yeah, but you need something additional.

      Since you first have to GRAB that particular element/field to check if you should validate it or not.

      So basically you need to have that ID in case to easily grab this element, but you can still achieve what you want.

      Leave ID alone, but you can add a CLASS to that field, it can be:

      class=”validate”

      And then you could do something like:

      if ($(‘#yourElement’).hasClass(‘validate’)) {
      // validation script goes here
      }

      It can be done in many different ways – thing is, you have to plan it before you start building it. I didn’t need something like you do, so I didn’t optimize script for that.

      But you can use the method above, it will work just fine. You just have to figure something out with your IDs. For example: why do you remove them? Instead of removing the field, you can leave them and make them:

      disabled=”disabled”

      That way user won’t get to change it anymore, but the filed will still be there. Let me know how it worked out, cheers.

      0
      • KLM

        Thursday, May 13th, 2010 00:29

        21

        Michal, this is working really well. I am stuck on one thing, I am trying to incorporate the following CC luhn javascript and can’t seem to get it to work. How do I check the the value is = 0; i -= 2) {
        sum += Array (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) [parseInt (cc.charAt (i), 10)];
        }
        for (i = cc.length – 1; i >= 0; i -= 2) {
        sum += parseInt (cc.charAt (i), 10);
        }
        return (sum % 10) == 0;
        }

        0
  • Michal Kozak

    Wednesday, May 5th, 2010 15:59

    15

    Not at all, glad it’s helpful.

    0
  • Michal Kozak

    Tuesday, May 4th, 2010 22:11

    14

    Thank you all very much for kind word :).

    As long as we’re on taht topic – I’m currently developing new, standalone JavaScript library, fully dedicated to form validation. It aims to provide very easy, simple, and highly customizable validation. I hope it will be released this year :).

    0
  • KLM

    Tuesday, May 4th, 2010 18:37

    8

    If I set a form field to display:none how do I get the validation to ignore those fields?

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:04

      10

      Simply don’t apply any validation to the that particular field :).

      0
      • KLM

        Tuesday, May 4th, 2010 22:13

        9

        Hi Michael, thanks for this awesome validation. Sometimes the field is required if it’s displayed and not if it’s hidden. I’m might have to create multiple validation scripts to call when needed.

        0
  • Ryan Turki

    Tuesday, May 4th, 2010 11:44

    7

    Great tut Michal ! Thanks

    0
  • joddy street

    Tuesday, May 4th, 2010 08:13

    6

    this is so far the best tute i have read about jquery form validation. loved the effect

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:08

      13

      Thank you, I appreciate it a lot. Hope to give you some new stuff, soon.

      0
  • Jared Detroit

    Monday, May 3rd, 2010 20:05

    3

    This is great! I’ve been telling myself I need to learn more jquery and this is a perfect example of not only what I need for my website but how to actually do it. Thanks for the complete example!

    0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:05

      11

      Glad I could help :). Just remember that this is just an example. It can be done much better, and of course has to be tweaked to your needs.

      0
  • Carli

    Monday, May 3rd, 2010 13:30

    2

    Well the date validation is a bit bugy, date format is like dd-mm-yyyy, and if I enter 15-15-2010, the date is valid, but we all know that there is only 12 months in one year. ;) In LIVE example …

    0
    • Michal Kozak

      Monday, May 3rd, 2010 19:07

      5

      Yup :), it just checks if the format is correct, nothing more (so like 2digits-2digits-4digits).

      This is just an example, remember :). There’s a room for improvement, changes and rewriting, can be done in many different ways, like with everything.

      It should be treated like something you can build your own validation upon, nothing more.

      0
      • BBoy

        Friday, June 10th, 2011 23:22

        39

        Hi!

        cool tutorial!
        I still have one question, if you find the time to answer it.
        I was looking all around google but I couldn’t find how to change the date format from dd-mm-yyyy to just yyyy.

        i tried like this:
        /^[1-2][0-9][0-9][0-9]}$/;
        and
        /^[0-9]{4}$/i;

        but none worked. Maybe someone knows why.
        Thank for your time and for the nice tut!

        cheers!

        0
  • Keiron Lowe

    Monday, May 3rd, 2010 13:48

    1

    Fantastic Tutorial, I love this website :D
    I’m assuming this doesnt send the email, this is just the validation?

    0
    • Michal Kozak

      Monday, May 3rd, 2010 19:04

      4

      Thanks a lot :).

      0
    • Michal Kozak

      Tuesday, May 4th, 2010 22:07

      12

      In the example, it sends the data you put into form field, but that data is not processed in any way :). It actually sends it to 1stwebdesigner’s home page, where it’s just NOT taken care of :).

      0

Comments are closed.

54.237.197.160 - unknown - unknown - US