JavaScript Tip of the Week for September 9, 1996: Forms Validation | WebReference

JavaScript Tip of the Week for September 9, 1996: Forms Validation

JavaScript Tip of the Weekfor September 9, 1996: Forms Validation

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.


The Form
E-Mail Address:
Name:

As you can see, 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 submited:
    <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 the e-mail page and it works great. Now you can apply forms validation to your forms too.

Source