Form Verification: The Right and Wrong Way
Dateline: 09/21/97
When making a web form, it is often necessary to require a
user to enter certain information such as his or her name or
email address. To keep from sorting through empty form records,
many administrators insert either CGI or JavaScript code to
prevent this from happening. The keener ones use JavaScript,
because they know that putting the code in the CGI program will
cause unnecessary stress on the server.
Let's assume you're going to make a form of this sort, and you
want to be among the keen administrators who decide to use
JavaScript. How do you make the JavaScript review the user's
input before submission? Well, there are two ways. If you go by
the example listed in the
Netscape JavaScript Authoring Guide, as I once
made the mistake of doing, you will encounter some serious
compatibility problems.
Netscape's Example suggests that you create a
fake submit button that calls a JavaScript function to do the
verification. The JavaScript function will then alert the user if
there is incorrect information, or submit the correct form using
the
submit() method. Here is an example of the fake
submit button:
<INPUT
TYPE="button" VALUE="Submit"
onClick="validateForm()">
This implementation will work fine if the user's browser is
fully supportive of JavaScript. If it is not, then you have just
created a completely useless screen full of buttons and text
boxes, because the JavaScript-impaired user has no way of
submitting this form.
If you make this mistake, webmaster@yourcompany.com will
quickly fill up with complaints about your form that doesn't
work. That JavaScript didn't save you much hassle, now that you
have to reply to 10 emails per day explaining to users that they
need to upgrade their browser.
How do you get the best of both worlds? Assign a value to the
onSubmit event handler in the form, and create
the rest of the form just like you would any other; submit button
and all. Like this:
<FORM
NAME="UserInfo"
ACTION=/old?u=http%3A%2F%2Fjavascript.about.com%2Flibrary%2Fweekly%2F%26quot%3B%2Fcgi-bin%2FsubmitUserInfo.pl%26quot&y=1999
METHOD="post" onSubmit="return
validateForm()">
With this example, the validateForm() function will return
true if the form is to be submitted, or will return false if the
form should not be submitted. Under this implementation, browsers
that do not recognize JavaScript will pass right over the
onSubmit property, and the form will be submitted with possible
errors. At this point, the CGI program can be written to handle
any errors that make it through the JavaScript, keeping user
complaints to a minimum.
Previous
Features
|