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

by Paul Adams and Apple Developer Connection

Any sort of interactive site is going to have form inputs -- a place where your users input who they are, what they want to buy, where they live, and so forth. This data is passed to whatever handles your back end -- a Perl CGI script, a PHP engine, a database like Oracle, or some other technology you've invested in. Whatever system is back there, you can bet that it doesn't appreciate having its time wasted with bogus information, and chances are the user doesn't appreciate it either. If the data the user submits to the CGI contains an error, there will be a noticeable lag -- typically several seconds -- before the information travels over the Internet to the server, is examined on the server, and then returns to the user along with an irritating error message.

If you run a little preliminary validation of the user's form input before the form is submitted, there will be no wait time. Client-side validation is instantaneous because it doesn't have to transmit any data. JavaScript catches any erroneous data the user enters before it goes anywhere.

Double-checking the data on the server remains necessary, in case the user has turned JavaScript off or somehow finds a way to circumvent the client-side validation, either maliciously or by accident. For the majority of your users, JavaScript form validation will save a lot of time up front.

The Script's Purpose

This script accompanies an HTML form. When the user clicks the Submit button on the form, the form data is sent to a JavaScript validation function that checks each aspect of the input to make sure that it is in the appropriate format. Each form element is evaluated according to specified criteria. If the script finds an error in one of the fields, it sends back a warning explaining how the string doesn't conform. The fairly robust string-handling and regular-expression techniques available in JavaScript handle this checking process.


A master function, called checkWholeForm() is placed at the top of the page that contains a form.

function checkWholeForm(theForm) {
    var why = "";
    why += checkEmail(theForm.email.value);
    why += checkPhone(theForm.phone.value);
    why += checkPassword(theForm.password.value);
    why += checkUsername(theForm.username.value);
    why += isEmpty(theForm.notempty.value);
    why += isDifferent(theForm.different.value);
    for (i=0, n=theForm.radios.length; i<n; i++) {
        if (theForm.radios[i].checked) {
            var checkvalue = theForm.radios[i].value;
    why += checkRadio(checkvalue);
    why += checkDropdown(theForm.choose.selectedIndex);
    if (why != "") {
       return false;
return true;

This function calls a series of subfunctions, each of which checks a single form element for compliance with a specific string format and returns a message describing the error. If the function returns an empty string, we know the element complies.


Here's the routine that checks to see if the user entered anything at all in the username field. (We'll use the same routine to check each form field for blankness.)

function checkUsername (strng) {
 var error = "";
 if (strng == "") {
    error = "You didn't enter a username.\n";

We pass the value of the username field to this function, which compares that value to an empty string (""). If the two are the same, we know that the username field is blank, so we return the warning string to our master function. If it's not blank, we move along to the next hurdle. We want to permit only usernames that are between 4 and 10 characters. We check the length of the string, and reject it if it's too short or too long.

if ((strng.length < 4) || (strng.length > 10)) {
    error = "The username is the wrong length.\n";

Comment on this articleCertainly using form validation before the CGI script is submitted to the server is nothing new, but it remains valuable. Are you using any variations on this theme?
Post your comments

Next, we want to forbid certain characters from appearing in usernames. Specifically, we want to allow only letters, numbers, and underscores. We can test for that using regular expressions and the test() method. The regular expression functions found in JavaScript 1.2 are similar to Perl's regular expressions, with a bit of simplification when it comes to syntax. If you know Perl, you should have no trouble wielding JavaScript's regular expressions. The JavaScript regular expression /\W/ is a standard character class that's handily predefined to mean "any character other than letters, numbers, and underscores." So we set the variable illegalChars equal to that regular expression, and then test the username string against that variable to see if a match is found. If it is, we throw up a warning.

var illegalChars = /\W/;
  // allow only letters, numbers, and underscores
    if (illegalChars.test(strng)) {
       error = "The username contains illegal characters.\n";

By now, we've run the username through three tests. If it's passed all three, it's OK by us. We give the username a passing grade and move along to the next field.


For the password field, we want to constrain the length again (this time, we'll keep it between 6 and 8 characters), and we want to allow only letters and numbers -- no underscores this time. So we have to use a new regular expression to define which characters we're banning. This one, like the last one, includes \W -- everything but letters, numbers, and underscores -- but we also need to explicitly mention underscores, so as to permit only letters and numbers. Hence: /[\W_]/.

function checkPassword (strng) {
 var error = "";
 if (strng == "") {
    error = "You didn't enter a password.\n";
    var illegalChars = /[\W_]/; // allow only letters and numbers
    if ((strng.length < 6) || (strng.length > 8)) {
       error = "The password is the wrong length.\n";
    else if (illegalChars.test(strng)) {
      error = "The password contains illegal characters.\n";

When it comes to passwords, we want to be strict with our users. It's for their own good; we don't want them choosing a password that's easy for intruders to guess, like a dictionary word or their kid's birthday. So we want to insist that every password contain a mix of uppercase and lowercase letters and at least one numeral. We specify that with three regular expressions, a-z, A-Z, and 0-9, each followed by the + quantifier, which means "one or more," and we use the search() method to make sure they're all there:

else if (!((strng.search(/(a-z)+/))
  && (strng.search(/(A-Z)+/))
  && (strng.search(/(0-9)+/)))) {
  error = "The password must contain at least one 
    uppercase letter, one lowercase letter,
    and one numeral.\n";

Pages: 1, 2

Next Pagearrow