Feb 14, 2009

Form Input Validation JavaScript

Many websites, like thesitewizard.com, have a feedback form of some sort so that visitors can make comments to the webmasters. If you have such a form on your site, I'm sure that from time to time, you would have received the results of your form with some essential field (like the email address or the visitor's name, or even the feedback itself) omitted.

Don't worry - this is a common problem. One way around it is to validate the essential fields with a simple JavaScript.

To do this, you will need to add a call to your validation function when the form is submitted. You do this by adding a "onsubmit" attribute to your FORM tag, like the following (keep it on one line if possible):

< form action="mailto:yourname@yourdomain.com" method="post" onsubmit="return checkform(this);" >

If the field you want to validate is something like:

< input type="text" name="email" / >

then your validation routine will look like the following (put it, say, in the HEAD of your document):


You will need to replace the "email" in both the "name" attribute of the INPUT tag as well as the function checkform to the actual name of the field you want to check. For example, if you want to check a field called "fullname", replace all instances of "email" in the function with "fullname".

The function begins by checking that the field named "email" is not an empty string. If it is, it will call the alert() function to display a dialog box with the message "Please enter your email address." It then calls form.email.focus() to place the text cursor in the email field for the convenience of the visitor and returns "false" to prevent the form from being submitted. On the other hand, if the field was not empty, nothing is executed and the form is submitted as usual.

What if you want to check more than one field? Simply copy everything from the
// ** START **
line to the
// ** END **
line and place it immediately below the existing
// ** END **
line, before the "return true;" statement. Then change all occurences of "email" in the new block to the name of the field you wish to check. You can duplicate that procedure as many times as you have fields to check.

No comments:

Boorkmark & Share

Bookmark Options