Javascript Client-Side Validation

Introduce scripting to your repetoire with Web page validations in JavaScript.

by Chris Barlow

If you want to call yourself an interactive developer, you're going to need some scripting in your repertoire. A good place to start is writing JavaScript functions to validate fields on a Web page. So make sure you have access to a Web server for testing the simple code we'll use in this column.

 Premier Members: Download the code
for this article

 Registered Members: Download the code
for entire issue

Not a premier member?
Upgrade now!

The first Web browsers could only display formatted text and images from HTML. Although they could display an HTML form with fields like text boxes and check boxes, these forms were processed at the server, usually with Common Gateway Interface (CGI) programs or PERL scripts. Today's popular browsers include powerful scripting engines that allow many functions to be performed at the client side, saving the roundtrip over the network. As Dynamic HTML (DHTML) becomes more prevalent, you'll be able to develop powerful applications that run within the browser on the client. In the meantime, you can use scripting to take some of the load off the server and the network. Unless your Web pages are only accessed on an Intranet, where you can control the browser used, Java-Script is the only common scripting language you can count on.

One of the most common problems facing an interactive developer is validation of form data. Are the required fields filled in? Are they filled in with the correct formats? Do the fields make sense when compared to other fields on the form? Standard HTML only allows minimal validation to limit the maximum length of a text field. For example, the simple form below has a single text field with a display length of 35 characters and a maximum length of five characters. The browser won't let you enter more than five characters in the field:

<html><head>
<title>Form1: MaxLength 
   Field Validation</title>
</head><body>
<form>
<p>Enter your email address
   <input Type="text" Size="35" 
   Maxlength="5"> </p>
</form></body></html>

Note that this form is good only for testing since it has no submit button or form action to return the contents of the field to the Web server.

Script Validation
If you want to check more than the maximum length of a field, you'll need to add some form processing. Some processing needs to take place at the server. For example, checking to see if a user is registered in the user database, probably requires access to a database on the server. However, much of the field validation can take place on the client.

To validate the fields on a form when the user clicks the submit button, you'll need to use the onSubmit event to call a validation function. One of the problems I had when first working with JavaScript in HTML forms was finding an easy way to test successful form submission. Normally, the Action property of a form submits the form data to an ASP file or script file on the Web server for processing. But when you're getting started with JavaScript you won't want the trouble of developing a forms processing script. To test if the submission was successful, add a simple action for the form that uses JavaScript to pop up a message box in the form action. If you see the message box, you know the form has passed your validation tests and will be submitted to the Web server.

To ensure that the e-mail field is not blank, add the code in the onSubmit event using the not equal operator (!=) and comparing the value property of the e-mail field to a null string. Finally, add a Name property for the text field and a standard Submit button:

<form 
   Action="javascript:alert('OK')" 
   Method="POST"
   onSubmit="return Email.value != '' ">
<p>Enter your email address
    <input Type="text" Size="35" 
   Maxlength="5" Name="Email"> </p>
  <p><input Type ="submit" 
   Name ="Action" Value="Submit"> </p>
</form>

If you click the Submit button without making an entry in the e-mail field, the statement in the onSubmit event evaluates to False. The form will not be submitted, the form action will not be called, and the OK message box will not appear. If you make an entry in the e-mail field, the statement returns True when you click the submit button and you will see the message box (see Figure 1).

Obviously, this simple example only works for a single field. To evaluate the fields on a form you'll need to call a function in the onSubmit event. Change your code to call a function called "Validate" and pass a pointer to the form with the this argument:

<form 
   action="javascript:alert('OK')" 
   Method="POST" 
   onSubmit="return Validate(this)">

If you split the validation process into several functions you'll be able to develop generic routines to use with all your forms. The main Validate function, called in the onSubmit event, will call several generic functions for the different fields on your form, starting with the CheckEmail function. The entire form will be passed to the Validate function, but you will only pass individual fields to the generic functions.

Start by identifying the script language as JavaScript, then adding the comment symbol so the browser won't try to display your JavaScript code. Then declare the Validate function with an argument of form. Remember, JavaScript is case-sensitive. When you write JavaScript code, function works but Function returns an error. Add an If...Else statement that returns False if the function CheckRequired returns False, otherwise it returns True. Note that the code is written this way, rather than return (CheckRequired(form.Email)), to allow room for additional If statements to call more validation functions for other fields:

<script LANGUAGE="javascript">
<!--
function Validate(form)
{
if (!CheckRequired(form.Email))
   {return (false);}
else
   {return (true);}
}

The CheckRequired function, which receives a single field as an argument, checks the length of the field and, if it is zero, displays a message box and uses the focus method of the field to set the entry cursor to that field. Note the slightly different form of the If statement used in this function. When the If statement is True the return statement is executed and no more lines of this function are executed. When the If statement is False processing "falls through" the rest of the statement and simply returns True. One of the things I like about programming is that there are many ways to solve the same problem. However, when you code a function you need to consider how to make it easy for others to understand:

function CheckRequired(field)
{
if (field.value.length == 0)
   {
   alert("Please enter the required 
      field");
   field.focus();
   return (false);
   }

return (true);
}

You can easily add other function calls to the Validate function to check other rules for other fields. For example, the CheckEmail function performs special validation of an e-mail address to enforce the rule that a valid e-mail address must contain an @ sign and a period. This function uses JavaScript's indexOf statement to find the position of a character within a field. The statement searches the string for the specified character. If the character is not in the field the statement returns -1. If the character is contained in the string, the zero-based character position is returned. You can also specify a starting position as an optional second parameter to search only a portion of the string. If the string does not contain the character, the function displays a message box and uses the focus method of the field to set the entry cursor to that field:

function CheckEmail(field)
{
if (field.value.indexOf("@") == -1)
   {
   alert("Please enter a valid Email Address");
   field.focus();
   return (false);
   }
if (field.value.indexOf(".") == -1)
   {
   alert("Please enter a valid Email Address");
   field.focus();
   return (false);
   }

return (true);
}

Another common validation is ensuring a field is a particular minimum length. This function is similar to CheckRequired. But the MinLength function demonstrates passing multiple arguments to a function and creating an alert string of concatenated literals and a variable using the concatenation operator (+):

function MinLength(field,len)
{
if (field.value.length < len)
   {
   alert(
   "Please enter at least " + 
   len + " characters");
   field.focus();
   return (false);
   }
else
   {return (true);}
}

You may need to ensure that a field is in a certain format. For example, a United States federal tax identification number is either in the format of a Social Security number (111-11-1111) or an Employer Identification Number (11-1111111). It would be nice to have a function to validate the format of a tax ID field.

Add another field called "TaxID" with a maximum length of eleven characters to your form with this line of HTML:

<p>Social Security or EIN Number
    <input TYPE="TEXT" SIZE="11" 
   MAXLENGTH="11" NAME="TaxID"></p>

Write a function called "CheckTaxID" that checks for the two possible formats. Use JavaScript's logical AND (&&) operator to combine several statements into a single If statement. If there is a hyphen in the third character and the field length is ten, then the format is valid for an Employer Identification Number, so return True. If there is a hyphen in the fourth character, and the seventh character and the field length is eleven, then the format is valid for a Social Security number so return True. Otherwise, display a message box, set the focus to the field, and return False:

function CheckTaxID(field)
{
if ((field.value.indexOf("-") == 2) 
   && (field.value.length == 10))
      {return true;}

if ((field.value.indexOf("-") == 3) 
   && (field.value.indexOf("-",4) == 6) 
   && (field.value.length == 11))
      {return true;}

alert("Please enter a valid TaxID");
field.focus();
return (false);
}

You can also write a validation function to check one field on a form against another. For example, add two more fields to the form of type PASSWORD so that the browser displays asterisks for characters that are typed (see Figure 2):

<p>Enter Password <input 
   TYPE="PASSWORD" SIZE="8" 
   MAXLENGTH="8" NAME="PW"> </p>
<p>Confirm Password <input 
   TYPE="PASSWORD" SIZE="8" 
   MAXLENGTH="8" NAME="PWC"> </p>

Then write a CheckPW function that accepts two fields as arguments. Note you can call the MinLength function you have already written to make sure the password is at least five characters. Use the not equal operator (!=) to make sure the two fields agree, otherwise return an appropriate error:

function CheckPW(fld1,fld2)
{
if (!MinLength(fld1,5))
   {return (false);}

if (fld1.value != fld2.value)
   {
   alert(
      "The password fields do not agree!");
   fld1.focus();
   return (false);
   }

return (true); 
}

The neat thing about these field validation procedures is, since you are passing fields as arguments, they will work on any of your HTML forms. The only function you need to modify is the first Validation function so that it calls the appropriate field functions for the fields on the form (see Listing 1). Use the complete HTML page, form4.htm, as a basis for any additional validation that you need to perform.


Chris Barlow is president of SunOpTech, a developer of document-management, decision-support, and supply-chain applications including the ObjectBank, ObjectOrder, and ObjectJob Systems. He holds two U. S. Patents related to software for decentralized distributed asynchronous object-oriented and scheduling systems. Chris, who is a frequent speaker at VBITS, Tech·Ed, and DevDays and has been featured in two Microsoft videos, holds degrees from Harvard Business School and Dartmouth College. Reach Chris at Chris@VBExpert.com or through his Web server at http://www.VBExpert.com.