HTML Writers Guild Guild Operations Newsletters Tips Feb 00b - PJansen

HWG-News Tips Late February 2000

Form Validation Tip -- Submitted by Phil Jansen

HWG-News features member-submitted "tips" in each issue, in the space between articles and announcements. This useful tutorial was too long to run as a tip, but has been provided here as a separate page:

Forms validation is a very useful aspect of JavaScript. It can be used to check over a given form and if it finds any problems, such as a blank input box or an invalid e-mail address, it can notify the user and not waste time sending it to a server. Aside from a few modifications to the form tag, its just like any other script. Try out this sample form by leaving an input empty or putting in an e-mail address without an @ sign.

Sample only
The Form
E-Mail Address:
Name:

 If you forget to enter certain data into the form it will alert you and cancel the submission. If you do enter all the correct info it will send the form (not this bogus one though). For future reference, you should know that the form is named theform, and its two inputs are named email and user_name.

The first and most important code in forms validation is an event handler in the form tag. This event handler, onSubmit, must return true for the form to be submitted:

    <FORM 
     NAME="theform" 
     ACTION="mailto:" 
     METHOD="POST" 
     ENCTYPE="multipart/form-data"
     onSubmit="return formCheck()">

When the submit button is pressed, the event handler is triggered; it in turn runs function formCheck() which makes sure there are no errors in the form:

function formCheck() 
    {
        if (document.theform.email.value.indexOf("@") == -1 ||
            document.theform.email.value == "") 
        {
        alert("Please include a proper email address.");
        return false;
        }
       
        if (document.theform.user_name.value == "") 
        {
        alert("Please put in a name.");
        return false;
        }
    }

First, formCheck() determines if the email input has an @ sign in it or is empty. If either of these scenarios are true, it alerts the user and returns false so the form will not be submitted. Then, it determines if the user_name input is empty. If it is, it also alerts the user and returns false. Either way, it won't allow the form to be submitted unless it has been filled out to a reasonable extent.

I'd say this is a useful tip for anyone with a lot of forms coming their way. I use it on an e-mail page and it works great. Now you can apply forms validation to your forms too.

Phil Jansen
Webmaster
webstudio@icon.co.za

More HWG Resources on Javascript


[Valid HTML 4.0!]
This page is maintained by editor@hwg.org. Last updated on 19 February 2000.
Copyright © 2002 by the International Webmasters Association/HTML Writers Guild.