Javascript Form Validation


There's nothing more troublesome than receiving orders, guestbook entries, or other form submitted data that are incomplete in some way. You can avoid these headaches once and for all with Javascript's amazing way to combat bad form data with a technique called "form validation".

The idea behind Javascript form validation is to provide a method to check the user entered information before they can even submit it. Javascript also lets you display helpful alerts to inform the user what information they have entered incorrectly and how they can fix it. In this lesson we will be reviewing some basic form validation, showing you how to check for the following:

  • If a text input is empty or not
  • If a text input is all numbers
  • If a text input is all letters
  • If a text input is all alphanumeric characters (numbers & letters)
  • If a text input has the correct number of characters in it (useful when restricting the length of a username and/or password)
  • If a selection has been made from an HTML select input (the drop down selector)
  • If an email address is valid
  • How to check all above when the user has completed filling out the form

This lesson is a little long, but knowing how to implement these form validation techniques is definitely worth the effort on your part. Remember to check out Tizag's HTML forms lesson if you need to brush up on your form knowledge.

Form Validation - Checking for Non-Empty

This has to be the most common type of form validation. You want to be sure that your visitors enter data into the HTML fields you have "required" for a valid submission. Below is the Javascript code to perform this basic check to see if a given HTML input is empty or not.

Javascript Code:


// If the length of the element's string is 0 then display helper message
function isEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return true;
	}
	return false;
}

The function isEmpty will check to see that the HTML input that we send it has something in it. elem is a HTML text input that we send this function. Javascriptstrings have built in properties, one of which is the length property which returns the length of the string. The chunk of code elem.value will grab the string inside the input and by adding on length elem.value.length we can see how long the string is.

As long as elem.value.length isn't 0 then it's not empty and we return true, otherwise we send an alert to the user with a helperMsg to inform them of their error and return false.

Working Example:

<script type='text/javascript'>
function isEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus();
		return true;
	}
	return false;
}
</script>

<form>
Required Field: <input type='text' id='req1'/>
<input type='button' 
	onclick="isEmpty(document.getElementById('req1'), 'Please Enter a Value')"
	value='Check Field' />
</form>

Display:

Required Field:

Validating a Form - All at Once

If you've made it this far I commend you, but we're not done yet! The final step is to be able to perform all of these validation steps when the user is ready to submit their data.

Each form has a Javascript event called onSubmit that is triggered when its submit button is clicked. If this even returns 0 or false then a form cannot be submitted, and if it returns 1 or true it will always be submitted. Wouldn't it be perfect if we could somehow make an if statement that said "If the form is valid submit it (1) else don't submit it (0)"? Well with a master formValidator function we can do just that.

formValidator will be somewhat like a list of checks that we want to do before a form is submitted. But before we can decide what we want to check for, we need to have our form!

HTML Form Code:

<form onsubmit='return formValidator()' >
First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />

Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
	<option>Please Choose</option>
	<option>AL</option>

	<option>CA</option>
	<option>TX</option>
	<option>WI</option>
</select><br />

Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' /><br />
</form>

That's a lot of data to verify and the first thing we would probably want to check is that each field was at least filled out. To check for completion we will ensure no fields are empty and that the SELECT field has a selection. Here are the starting pieces of our master validation function formValidator.

Javascript Code:

function formValidator(){
	// Make quick references to our fields
	var firstname = document.getElementById('firstname');
	var addr = document.getElementById('addr');
	var zip = document.getElementById('zip');
	var state = document.getElementById('state');
	var username = document.getElementById('username');
	var email = document.getElementById('email');
	
	// Check each input in the order that it appears in the form!
	if(isAlphabet(firstname, "Please enter only letters for your name")){
		if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
			if(isNumeric(zip, "Please enter a valid zip code")){
				if(madeSelection(state, "Please Choose a State")){
					if(lengthRestriction(username, 6, 8)){
						if(emailValidator(email, "Please enter a valid email address")){
							return true;
						}
					}
				}
			}
		}
	}
	
	
	return false;
	
}

The first part of this function is where we create easy references to our HTML inputs using the getElementById function. These quick references will make our next block of code much easier to read!

The second part uses a bunch of embedded if statements to see whether or not each field has the correct type of data. If every single one of those fields we check validates, then we'll return true and the form will be submitted successfully.

However, if just one of those if statements fails then the return false at the end of the function is reached and prevents the form for being submitted.

As you can see this function really does do quite a lot, definitely earning the title of formValidator. Notice how this one function references all of the functions we have covered in this lesson. By placing all of these checks in a central location you make your code easier to read and easier to change around in the future.

Now let's put all the necessary and HTML together and try it out!

All Together Now

Below we have taken the HTML form code and the new function formValidator and plugged in all the other form validation functions taught in this lesson that are referenced in formValidator.

HTML & Javascript Code:

<script type='text/javascript'>

function formValidator(){
	// Make quick references to our fields
	var firstname = document.getElementById('firstname');
	var addr = document.getElementById('addr');
	var zip = document.getElementById('zip');
	var state = document.getElementById('state');
	var username = document.getElementById('username');
	var email = document.getElementById('email');
	
	// Check each input in the order that it appears in the form!
	if(isAlphabet(firstname, "Please enter only letters for your name")){
		if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
			if(isNumeric(zip, "Please enter a valid zip code")){
				if(madeSelection(state, "Please Choose a State")){
					if(lengthRestriction(username, 6, 8)){
						if(emailValidator(email, "Please enter a valid email address")){
							return true;
						}
					}
				}
			}
		}
	}
	
	
	return false;
	
}

function isEmpty(elem, helperMsg){
	if(elem.value.length == 0){
		alert(helperMsg);
		elem.focus(); // set the focus to this input
		return true;
	}
	return false;
}

function isNumeric(elem, helperMsg){
	var numericExpression = /^[0-9]+$/;
	if(elem.value.match(numericExpression)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphabet(elem, helperMsg){
	var alphaExp = /^[a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function isAlphanumeric(elem, helperMsg){
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(elem.value.match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

function lengthRestriction(elem, min, max){
	var uInput = elem.value;
	if(uInput.length >= min && uInput.length <= max){
		return true;
	}else{
		alert("Please enter between " +min+ " and " +max+ " characters");
		elem.focus();
		return false;
	}
}

function madeSelection(elem, helperMsg){
	if(elem.value == "Please Choose"){
		alert(helperMsg);
		elem.focus();
		return false;
	}else{
		return true;
	}
}

function emailValidator(elem, helperMsg){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
</script>

<form onsubmit='return formValidator()' >

First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
	<option>Please Choose</option>

	<option>AL</option>
	<option>CA</option>
	<option>TX</option>
	<option>WI</option>

</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>

Display:

First Name:
Address:
Zip Code:
State:
Username(6-8 characters):
Email: