There are dozens of misconceptions around what you can build with jQuery. The library is extensible enough that you can target a whole range of HTML elements and perform some very complex data checks. Form validation is one such problem which jQuery can solve – and to be more specific e-mail contact form validation.

In the tutorial below I’ll demonstrate how you can build a jQuery-powered form validation script. We will hide the submit button until the user has entered a name, a valid e-mail address, and some message text. This approach on form validation is slightly different than the norm. But it works well enough to keep spam submissions to a minimal.

jQuery input form validation script demo screenshot

Live DemoDownload Source

Getting Started: Building the Form

Let me start off by explaining how I’ve setup this form document. The entire content area is wrapped and centered in an 800px block. Additionally each of the input fields are wrapped in a div with the class .rowbox.

		<div class="rowbox">
			<label for="name">Name</label>
			<input type="text" id="name" name="name" class="txtbar req" tabindex="1">
			<div class="infobox">
				Enter your full name, at least 3 letters required.
			</div>
		</div>

Inside this div we include the 3 main elements required for each piece: the label, the input field, and a smaller infobox off to the right side. This is only displayed when you click to focus on any of the four fields available. This info box is setup to change classes via jQuery as the user enters new text.

Then finally at the very bottom we have a submit button. I haven’t tied into any backend PHP/RoR because I feel that’s a bit out of the tutorial scope. However there are tons of simple tuts online for building an e-mail submission form on the server backend.

Processing Animations

With most of the CSS being standard properties and classes I feel we can move right into the jQuery code. There isn’t much to get out of our stylesheet except for a few animated classes which I will explain further down.

My demo page is pulling the latest jQuery 1.7.2 minified version from their code CDN. Additionally I’ve included a second script underneath which holds all of our custom code. I’ll move through this script in small portions so you can pick up the logic as we go along.

function checkValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-+\s]+")|([\w-+]+(?:\.[\w-+]+)*)|("[\w-+\s]+")([\w-+]+(?:\.[\w-+]+)*))(@((?:[\w-+]+\.)*\w[\w-+]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][\d]\.|1[\d]{2}\.|[\d]{1,2}\.))((25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\.){2}(25[0-5]|2[0-4][\d]|1[\d]{2}|[\d]{1,2})\]?$)/i);
    
    return pattern.test(emailAddress);
};

$(document).ready(function() {
	// hide the send button on default
	$("#sendbtn").css("opacity", 0);

At the very top I defined a custom function checkValidEmailAddress(). This uses a largely confusing regular expression to test against the user’s input string and validate for an e-mail address. You certainly aren’t expected to understand 100% how this code operates. But just understand that we do need this function for e-mail validation.

Then right underneath we open our $(document).ready() clause to setup all the default functionality. The first line targets our send button and manipulates the CSS opacity property to zero. Once the user provides correct information we can animate it back into existence.

Live Event Handlers

The rest of our jQuery script is dealing with two distinct user states. We need to check when the user focuses on a new input and when they de-focus(or blur) away from an input. Both of these actions require different methods to be performed.

$(".txtbar, .txtbox").live("focus", function(){
	var thelabel = $(this).prev();
	var infobox = $(this).next();
	var rowbox = $(this).parent();
	var currid = $(this).attr('id');
	var pxlchange = '-45px';
		
	if(currid == "subject") { pxlchange = '-90px'; }
	if(currid == "message") { pxlchange = '-60px'; }

	rowbox.addClass('colors');

Read up a bit on the jQuery live() handler if you are puzzled by the syntax. We basically need to pass in a value for the event handler – in this case when the user focuses on either our .txtbar or .txtbox elements. We then setup a few variables targeting elements in our current row. This makes editing the content much easier down the road.

The variable pxlchange is a value used to reposition the label text after the user has clicked on an input field. We need to move the label over to the left a certain distance, and this number is different for a couple of rows. With those values setup we also add a class .colors to the rowbox for a highlighted effect.

thelabel.animate({
	left: pxlchange
	}, 350, 'linear', function(){
	// animation complete
});
	
infobox.animate({
	opacity: 1.0
}, 350, 'linear', function(){
	// animation complete
});

Now the last two calls we need to perform are small animations on the page. First we slide the associated label text over to the left based on our current pxlchange value. Then second we slowly fade-in the opacity for our current row’s infobox statement. This offers tips to the user about each of the fields and which data is required.

I’ll explain the blur events quickly in the next section, then we’ll wrap up on the validation code.

Losing Form Focus

For now skip past the keyup event handler and move down to the bottom of our script. Here you’ll find a similar block of code as above, except now we’re testing for a blur event.

$(".txtbar, .txtbox").live("blur", function(){
	var thelabel = $(this).prev();
	var infobox = $(this).next();
	var rowbox = $(this).parent();
	var currid = $(this).attr('id');
		
	rowbox.removeClass('colors');
		
	infobox.animate({
		opacity: 0
	}, 400, 'linear', function(){
		// animation complete
	});
});

I’ve got most of the same variables set up targeting the row’s infobox, label, and parent rowbox element. When the user clicks away we actually only need to perform two distinct animations: removing the colored row background and re-hiding the infobox content. We don’t need to touch the label at all because once it moves over for the first time it should stay in place.

Validating On Key Up

Moving back upwards this next block of code is certainly the longest and most confusing. All of this logic is held inside our focus event handler because we only want to check validation if the user is actually typing inside a field! If they are just hitting keys with no focus then we have nothing new to validate against.

$(this).live("keyup", function(){
	var theval = $(this).val();
	var limitval = 3;
	var replacehtml = "";
	var nameinfohtml = "Enter your full name, at least 3 letters required.";
	var emailinfohtml = "Enter a valid e-mail address. We promise not to share this with <strong>anyone</strong>!";
	var subjectinfohtml = "Enter an e-mail subject if you'd like.";
	var messageinfohtml = "Lay into that keyboard(at least 10 chars) and let us know what's on your mind.";
			
	if(currid == "name") {
		replacehtml = nameinfohtml;
	} else if(currid == "email") {
		replacehtml = emailinfohtml;
	} else if(currid == "subject") {
		replacehtml = subjectinfohtml;
		limitval = 1;
	} else if(currid == "message") {
		replacehtml = messageinfohtml;
		limitval = 10;
	}

The variable limitval is a number representing the minimum required characters for validation in any form field. It it set to 3 by default since we only require 3 characters in the sender’s name. We reset this to 1 for the subject field(not a required field) and 10 for the message box.

Each of the HTML variables is a way to save the original infobox text in case we need it again. If the user enters a valid name then deletes characters less than 3 we need to let them know the name is no longer valid. This is the same case for the e-mail address and form message.

// checking against e-mail regex
if(currid == "email"){
	if(checkValidEmailAddress(theval)) {
		infobox.html("Looks good!");
		infobox.addClass('good');
	}
	else if(!checkValidEmailAddress(theval)) {
		infobox.html(replacehtml);
		infobox.removeClass('good');
	}
} 
else {
	// we use this logic to check for name+message fields
	if(theval.length >= limitval) {
		infobox.html("Looks good!");
		infobox.addClass('good');
	} else if(theval.length < limitval) {
		infobox.html(replacehtml);
		infobox.removeClass('good');
	}
}

Within this if/else statement is where we perform all the input validation. First we check if the user is focused on our e-mail input, and if so we use the regex validation function from earlier. Otherwise we check and see if the current value of the active field is equal to or longer than our minimum characters limit.

Notice that if the email validation fails or if the character count drops below the minimum we remove the .good class from the infobox and display our original tips again. This lets the user know that they need to re-enter correct data to have it be accepted.

Displaying the Submit Button

The very final phase of this key up event handler is to check when the form is 100% fully validated. Once the user has all 3 required fields setup properly, excluding subject, then we fade the submit button onto the page.

	// now we check if we can display the send button
	// much easier to just look for 'good class on the req fields
	if( $('#name').next().hasClass('good') 
	 && $('#email').next().hasClass('good')
	 && $('#message').next().hasClass('good') ) {
		// if all 3 boxes are good then we display our send button!
		// jquery validation complete
		$('#sendbtn').animate({
			opacity: 1.0
		}, 200, 'linear', function(){
			// display submitbtn animation complete
		});
	}
});

I’m checking validation against the current infobox for each input row. If the main three infoboxes still have a .good class then the data is all set. We then use our final .animate() function to fade in the submit button.

Again I haven’t setup any backend for the script, so right now the form just reloads index.html. But it wouldn’t be hard to couple the jQuery .ajax() method with a backend script to pass in all of the values via POST or GET.

jQuery Form input validation demo screen

Live DemoDownload Source Code

Conclusion

This form validation code is a bit off-center compared to other examples. We are using some fresh animations to give the form a personal touch. But functionality and website security are always important, so these should play a role in checking against a backend script too. Be sure and test out the live demo example above, plus download a copy of my source code to play with if you’re interested.

Posted by Jake Rocheleau

Jake is a writer & digital designer/illustrator. He writes about all things web and creative. Check out his website for work samples and follow his latest updates on Twitter @jakerocheleau.

Leave a reply

Your email address will not be published. Required fields are marked *