WebDeveloper.com �: Where Web Developers and Designers Learn How to Build Web Sites, Program in Java and JavaScript, and More!   
Web Developer Resource Directory WebDev Jobs
Animated GIFs
CSS
CSS Properties
Database
Design
Flash
HTML
HTML 4.01 Tags
JavaScript
.NET
PHP
Reference
Security
Site Management
Video
XML/RSS
WD Forums
 Client-Side
  Development

    HTML
    XML
    CSS
    Graphics
    JavaScript
    ASP
    Multimedia
    Web Video
    Accessibility
    Dreamweaver
    General
    Accessibility
    Dreamweaver
    Expression Web

    General

 Server-Side
  Development

    PHP
    Perl
    .NET
    Forum, Blog, Wiki & CMS
    SQL
    Java
    Others

 Site Management
    Domain Names
    Search Engines
    Website Reviews

 Web Development
  Business Issues

    Business Matters

 Etc.
    The Coffee Lounge
    Computer Issues
    Feedback




Client-Side Form Verification with JavaScript

Client-Side Form Verification with JavaScript

by Heidi Brumbaugh

JavaScript code runs on the user's machine, making it an ideal method to perform simple verification on form data before submitting it on to the server. Performing the checks on the client side saves the user from waiting for the data to travel way back to the server, and then (if there's a problem) waiting again for an error message.

My original JavaScript tutorial showed you how to "grab" the onSubmit event from a form. Here we'll take that a step further, running our verification procedures before we decide whether to allow the data to be sent along.

I also showed you how to add a NAME field to an image tag, so that you could refer to that specific image later. Turns out JavaScript uses this NAME field in many HTML tags, including the FORM tag and the form fields' tags. Recall the hierarchical nature of JavaScript wants you to identify items first by document, then by form, then by field name. Separate each identifying level in the hierarchy with periods. For example, if you have a form defined like this:

<FORM name="Customer"> Your name: <INPUT type=text name="FirstLast" size=30 maxlength=75 value=""> </FORM>

You would access the customer's name field like this:

document.Customer.FirstLast.value

Okay, we know how to intercept the onSubmit event and how to examine the form fields. Next we'll use a few simple scripting commands to analyze the data. First, let's establish a variable, called valid, that we'll use to keep track of whether the data is valid. Initialize this value with 1 (meaning, to start out with, we'll assume everything is peachy).

var valid = 1

Now let's make sure the user entered something into the name and email fields of the form. This is fairly straightforward; if the field is blank, the form is invalid. In JavaScript, a double-equals sign checks for equality.

 if (document.Customer.FirstLast.value == "") { valid = 0 } 

We can verify the email address the same way.

Strings Are Things

Next let's add a more sophisticated check for the phone number. Since we might have long distance numbers or international numbers, we won't be too strict. But we will make sure the number falls with certain parameters: it contains only numerals, spaces, and the following characters: ( ) - +

To analyze the characters the user typed into the form field, you need to know about strings. In programming, a string is a sequence of alphanumeric characters. In JavaScript, most values that contain letters and numbers are string objects.

One way to think about strings is to imagine a sheet of grid paper. Each square on the page is numbered, starting with zero. When you create a string, you put one character in the first square, then next character in the second square, and so on. You can perform operations on the entire string, or you can use the grid numbers as an index into the individual elements of the string, giving you a convenient way to analyze the characters one by one.

Here are the JavaScript commands, including several string properties and methods, used in the phone number verification routine:

for (initial condition; end condition; increment command) { }
Performs an operation a certain number of times. We'll use an index into the string we want to analyze. Thus the initial condition is the index equals zero, the end condition is the index has reached the end of the string, and each time through the loop we'll increment the counter by one.

StringName.length
This property of a string object returns the number of characters in the string.

StringName.charAt(position)
This method returns the character at the index position. Remember the first character index is 0, the last is length-1. For example, MyName.charAt(0) returns "H" if MyName is "Heidi".

StringName.indexOf(SearchString)
This method returns the position of SearchString inside a string, or -1 if SearchString is not found. The verification routine makes up a string containing all the valid phone number characters. The indexOf method compares each character in the string with this list of numbers. If -1 is returned for any character, the phone number is invalid.

Here's the final routine:

 function CheckPhoneNumber(TheNumber) { var valid = 1 var GoodChars = "0123456789()-+ " var i = 0 if (TheNumber=="") { // Return false if number is empty valid = 0 } for (i =0; i <= TheNumber.length -1; i++) { if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) { // Note: Remove the comments from the following line to see this // for loop in action. // alert(TheNumber.charAt(i) + " is no good.") valid = 0 } // End if statement } // End for loop return valid } 

One thing to note here is that valid is used in both CheckPhoneNumber and VerifyData. Because the variable is declared separately in each function (with the var statement), they are completely independent of each other. In programmerese, these variables are local. (In English, they are blissfully unaware of each other.)

Check out the complete example. There's a lot going on here, especially in the CheckPhoneNumber routine. To learn more about the commands used here, check out the syntax and examples at Netscape's JavaScript Reference. One thing you can do is to look up the String object, and see what other methods are available to you.




HTML5 Development Center


Recent Articles