Web DevCenter
oreilly.comSafari Books Online.Conferences.
MySQL Conference and Expo April 14-17, 2008, Santa Clara, CA

Sponsored Developer Resources

Web Columns
Adobe GoLive
Essential JavaScript

Web Topics
All Articles
Scripting Languages

Atom 1.0 Feed RSS 1.0 Feed RSS 2.0 Feed

Learning Lab

Form Validation
Pages: 1, 2


Related Reading

JavaScript: The Definitive Guide, 4th EditionJavaScript: The Definitive Guide, 4th Edition
By David Flanagan
Table of Contents
Sample Chapter
Full Description

Next we want to see if the email address the user entered is real. The most effective way to do this is to go out on the Net and ask the domain the user claims to hail from if that the person actually has an account. But this takes a big toll on the machine that's running the checks -- and it isn't possible with JavaScript anyway. With JavaScript we can check to see if the email string looks like an email address. We want it to follow this format: some characters, then an at symbol (@), then some more characters, then a dot (.), then two or three more characters, and that's it. This won't be perfect validation --it is possible to slip phony non-RFC-compliant addresses by it -- but it's normally good enough. If the pattern doesn't match, we reject the email address.

The regular expression that expresses the format goes something like this: /^.+@.+\..{2,3}$/. The carat (^) means the start of the string and the dollar sign ($) means the end of the string. By surrounding the rest of the regular expression with these characters, we ensure that we evaluate the entire string, rather than just a portion. Each .+ means "at least one character" -- the dot (.) means "any character"" and the plus sign (+), you recall, means "one or more." The .{2,3} portion means "two or three characters." And when we want to match a literal dot, we need to escape the character with a backslash. That's why we have \. there.

var emailFilter=/^.+@.+\..{2,3}$/;
if (!(emailFilter.test(strng))) { 
       error = "Please enter a valid email address.\n";

Again, we want to check to make sure that no forbidden characters have slipped in. For email addresses, we're forbidding the following: ( ) < > [ ] , ; : \ / "

var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/
if (strng.match(illegalChars)) {
   error = "The email address contains illegal characters.\n";


To validate a phone number, first we want to clear out any spacer characters, such as parentheses, dashes, spaces, and dots. We can do this with a regular expression and the replace() method, replacing anything that matches our regular expression with a null string. Having done that, we look at what we have left with the isNaN() function (which checks to see if a given input is Not A Number), to test if it's an integer or not. If it contains anything other than digits, we reject it.

var stripped = strng.replace(/[\(\)\.\-\ ]/g, '');
//strip out acceptable non-numeric characters
if (isNaN(parseInt(stripped))) {
   error = "The phone number contains illegal characters.";

Then we count the length of the number. It should have exactly ten digits -- any more or less, and we reject it.

if (!(stripped.length == 10)) {
	error = "The phone number is the wrong length.
	  Make sure you included an area code.\n";


We want to do a few more kinds of validation. If you present a license or something similar in a text box for the user to accept, you want to make sure that it hasn't been altered when the form is submitted. That's done very simply by comparing the submitted string with the string you were expecting.

function isDifferent(strng) {
  var error = "";
  if (strng != "Can\'t touch this!") {
     error = "You altered the inviolate text area.\n";

Alternately, you can use the onChange() method to catch the user in the act of modifying the text and stop them before they submit the form.


To make sure that a radio button has been chosen from a selection, we run through the array of radio buttons and count the number that have been checked. Rather than sending the whole radio object to a subfunction, which can be problematic (because the radio object has no property indicating which value has been chosen), we pre-process the radio form element in a for loop and send that result to a subfunction for evaluation.

for (i=0, n=theForm.radios.length; i<n; i++) {
   if (theForm.radios[i].checked) {
      var checkvalue = theForm.radios[i].value;
why += checkRadio(checkvalue);
function checkRadio(checkvalue) {
var error = "";
   if (!(checkvalue)) {
       error = "Please check a radio button.\n";
return error;    

check Dropdown()

Finally, we want to make sure that the user has selected an option from our drop-down menu (and not the first option, which isn't an option at all, but just a "Choose one" header). For this, we use the select object's selectedIndex property, which returns the index of the selected option. If the index is 0, we reject the input.

function checkDropdown(choice) {
    var error = "";
    if (choice == 0) {
       error = "You didn't choose an option
         from the drop-down list.\n";
return error;

Coding Challenges

Validation basically consists of comparing one thing to another, which is easy, especially with JavaScript. The part that requires a bit of ingenuity is creating the regular expressions. The more complex the expression, the harder it is to write. After some practice and immersion in the world of regular expressions, though, they can become second nature.

Code and Example:

View source of validate.js.

Try an example form.

Validation also comes in more complex flavors than we've covered here. For example, you may wish to validate a credit card number. An algorithm called the Luhn modulus-10 formula checks the validity of a given credit card number. In a case like this, there's no need to re-invent the wheel. You can grab a simple script from brainjar.com or a more complete version from JavaScript Source.

Using The Script

All of the functions are included in a file called validate.js, which can be called with the SRC attribute of a SCRIPT tag at the top of the form page. Or, if you wish, you can paste the contents of this file into the top of your HTML page. If you prefer, you can validate each form element as soon as the user moves on to the next element using the onBlur() event handler instead of onSubmit(). As always, remember to validate important form data on the back end as well, because most efforts at client-side validation can be spoofed.

Paul Adams is a freelance writer. He regularly contributes to a number of publications on topics including web programming, graphics, technology, and design.

Return to the JavaScript and CSS DevCenter.