Validating Form Fields Using JavaScript in FrontPage
This documentation is archived and is not being maintained.

Validating Form Fields Using JavaScript in FrontPage

Office 2003
 

Lisa Wollin
Microsoft Corporation

May 2004

Applies to:
    Microsoft® Office FrontPage® 2003
    Microsoft FrontPage 2002
    Microsoft FrontPage 2000

Summary: Learn how validate HTML form fields using JavaScript in Microsoft Office FrontPage 2003. This article assumes a general understanding of HTML and JavaScript. (16 printed pages)

Contents

Introduction
Getting Started
Writing the Validation Script
Connecting the Form to the Script
Associating Form Fields with Custom Script
Code Listing
Conclusion

Introduction

When you create forms, providing form validation is useful to ensure that your customers enter valid and complete data. For example, you may want to ensure that someone inserts a valid e-mail address into a text box, or perhaps you want to ensure that someone fills in certain fields.

Microsoft® Office FrontPage® 2003 allows you to create some custom validation within the form feature. (For more information on how to create form validation using the FrontPage form feature, see About creating forms in FrontPage 2003.) However, if the form validation provided in FrontPage does not suit your needs or the site on which you are working is hosted on a server that does not have FrontPage Server Extensions from Microsoft installed, you may need to create custom form validation.

Note   FrontPage Server Extensions are a set of programs that provide access to special FrontPage features, such as database processing, form processing, hit counters, and other built-in FrontPage components that require server-side processing.

You can provide custom validation for your forms in two ways: server-side validation and client-side validation.

Server-side validation incorporates code validation into a form handler. For example, you may have an ASP or ASP.NET application on the server that provides the functionality that your form needs for processing after a customer has submitted it. Because the code is stored on the server, server-side validation requires a roundtrip to the server. Sending data back and forth between the client and server can cause some delays. However, for some form functions, server-side validation is necessary. For example, if you have a form that populates a drop-down list based on the value of another form field, server-side processing may be needed to pull data from a database and populate the drop-down list.

Client-side validation provides validation within the browser on client computers through JavaScript. Because the code is stored within the page or within a linked file, it is downloaded into the browser when a user accesses the page and, therefore, doesn't require a roundtrip to the server. For this reason, client form validation can be faster than server-side validation. However, client-side validation may not work in all instances. A user may have a browser that doesn't support client-side scripting or may have scripting disabled in the browser. Knowing the limits of client-side scripting helps you decide whether to use client-side form validation.

This article explains how to provide client-side validation for forms that you create either by hand or by using the form tools within FrontPage. In addition, this article assumes a general understanding of HTML and JavaScript, although a thorough understanding is not required. For more information about HTML and Web scripting, see one or more of the following references.

Important   JScript is Microsoft's implementation of ECMAScript, as defined by the specification of the European Computer Manufacturers Association. Both JavaScript and JScript are ECMAScript-compliant languages. When referring to JavaScript in general, this article uses the generally accepted term "JavaScript." However, when referring to documentation on the Microsoft Developer Network (MSDN) Web site, this article uses the term "JScript."

Getting Started

To get started, you need a form. For the purposes of this article, paste the following form into a new page in FrontPage in Code view.

Note   To do this, create a new page, switch to Code view, and paste the following code between the <body> and </body> tags.
<form method="post" action="mailto:Frank@cohowinery.com">
    <p>Name: <input type="text" size="65"></p>
    <p>E-mail Address:  <input type="text" size="65" ></p>
    <p>Telephone: <input type="text" size="65"><br>
        <input type="checkbox"> Please do not call me.</p>
    <p> What can we help you with?
        <select type="text" value="">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55">  </textarea></p>
    <p><input type="submit" value="Send" name="submit"><br>
    <input type="reset" value="Reset" name="reset"></p>
</form>

Code Sample 1. Starting form code

As you work through this article, you are asked to add or change portions of the previous code.

Note   The previous code specifies an e-mail address for the Action attribute of the form property. For more information, see ACTION Attribute | action Property and form property. The action attribute tells the browser what to do when a user submits the form. If you want to test this form, change this e-mail address to your own e-mail address.

Assigning Names to Form Fields

In order to access your form fields in code, you need to assign names to the form and each of the fields. You do this by using the Name attribute. For more information see, NAME Attribute | name Property. You may assign any name you want that is composed of alphanumeric characters (without spaces), but to make writing the code easiest, you should provide a useful, friendly name for each of the fields. In addition, each of the fields should have a unique name.

Note   Generally, it is a good idea to provide a name attribute for each HTML element that you plan on accessing in code.

In the code provided previously you can find the following line.

<p>Name: <input type="text" size="65"></p>

When you add the name attribute, the code looks like the following:

<p>Name: <input type="text" size="65" name="Name"></p>

Use the following table to assign names to all of your form elements. In this table, Element refers to the name of the HTML element for the form field, Type refers to the value of the type attribute for the form field, and Label refers to the text to the left of the form field.

Element Type Label Name
FORM (not applicable) (none) ContactForm
INPUT text Name Name
INPUT text E-mail Address Email
INPUT text Telephone Telephone
INPUT checkbox Please do not call me. DoNotCall
SELECT text What can we help you with? Subject
TEXTAREA (not applicable) Comments Comment

Once you have assigned names for your form and all of the form elements, your form code should resemble the following code.

<form method="post" action="mailto:Frank@cohowinery.com" name="ContactForm">
    <p>Name: <input type="text" size="65" name="Name"></p>
    <p>E-mail Address:  <input type="text" size="65" name="Email"></p>
    <p>Telephone: <input type="text" size="65" name="Telephone"><br>
        <input type="checkbox" name="DoNotCall"> Please do not call me.</p>
    <p>What can we help you with?
        <select type="text" value="" name="Subject">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
    <p><input type="submit" value="Send" name="submit"><input type="reset" value="Reset" name="reset"></p>
</form>

Code Sample 2. Form code updated with name attribute values

Writing the Validation Script

Now that you have assigned names for the form and form fields, you are ready to start writing the script that handles the validation for the fields.

Important   JavaScript is case sensitive. If you are typing the JavaScript code in this article manually and receive errors, you should check that all casing is the same as shown in this article. Otherwise, you may want to review JScript Run-Time and Syntax errors.

Creating the Function

You need a custom function that you can later connect to the form. For more information about creating a function, see JScript Functions. A function is a piece of code that consists of one or more lines of script. A function can take arguments and can return values. The validation script in this article returns a Boolean value that specifies whether the data contained in the form is valid.

To create your own custom function, insert a SCRIPT element into the HEAD section of your form page; within the SCRIPT element, use the function statement to insert a function named ValidateContactForm. For more information, see function Statement. This code should look something like the following code sample.

<script>
function ValidateContactForm()
{

}
</script>

Code Sample 3. Starting script function

Creating Field Variables

To access the form fields within the code, you should create variables. For more information, see JScript variables. Variables allow you to temporarily store values. Variables are not required, but they make accessing each field easier. For example, without a variable, you would have to type document.ContactForm.Name every time you needed to access the Name field. However, after you assign a variable to the field, you can use the variable to access the field. Variables require less typing and help make your code more readable.

The contact form code in this article contains six fields to which you assigned name attribute values; therefore, you need six variables, one for each field. The following code shows the ContactForm Validation function with variables for the six form fields.

function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone; 
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;
}

Code Sample 4. Script function with variables

Note   If you type the previous code into your page, notice that FrontPage provides IntelliSense for your named fields.

Defining Required Fields

You may want to require that users type something for some fields on your form. By default, when you first create a form, all fields are optional. Therefore, if you want to ensure that users fill in certain fields, you need to tell the form validation function to check each field by checking the value of the field. In most cases, just checking whether the field contains a value is sufficient for a required field. In the following example, the if statement determines whether the Name field contains a value by checking whether the value of the Name field is equal to a empty string. For more information, see if. . .else Statement.

if (name.value == "")
{
    window.alert("Please enter your name.");
    name.focus();
    return false;
}

If the user clicks the Submit button without entering a value in the Name field, the browser displays a message to remind the user to enter a name. The Insertion Point is placed in the Name field, and the user is returned to the form. The return statement with a value of false is necessary so that the rest of the code doesn't execute. For more information, see return Statement.

For the contact form in this article, you also need a validation if statement for the comment field. The following code checks whether a user has entered a value in the comment field.

if (comment.value == "")
{
    window.alert("Please provide a detailed description or comment.");
    name.focus();
    return false;
}

You can add a similar if statement to verify that the user has selected an item from the What can we help you with drop-down list. In this case, you don't check the value of the field; you check the value of the selected item. The following code shows the validation for the What can we help you with drop-down list.

if (what.selectedIndex < 1)
{
    alert("Please tell us how we can help you.");
    what.focus();
    return false;
}

Items in a drop-down list or list box begin numbering at zero, so if the index of the selected item is less than 0, the user hasn't selected anything. However, the first OPTION element in the Subject field in the contact form is blank. (A space is used to keep the tag pair from being empty.) This technique allows no value to be displayed in the list when the form page first loads, so the first valid item in the list is numbered 1. Therefore, the previous if statement requires that the selected item index be less than 1.

Determining Whether Data Is Valid

In some cases, you may want to verify that the data is valid based on a specified format. For example, you know that all e-mail addresses contain an at symbol (@) and at least one period (.). For the e-mail address, the if statement needs to be slightly more detailed to check for the needed values. In addition, because you need to check for multiple values, you need multiple if statements. In this case, there are three if statements: one to check whether the e-mail field contains a value, the second to check whether the e-mail string contains an @ symbol, and the third to check whether the e-mail string contains a period.

The second and third if statements use the indexOf method to determine whether a string occurs within another string. For the e-mail address, you need to determine whether an @ symbol or a period occurs within the e-mail form field. If the value returned from the indexOf method is less than zero (or –1), the e-mail address is invalid, the validate function returns false, and focus is returned to the e-mail form field.

The following code shows validation for the Email field.

if (email.value == "")
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}

if (email.value.indexOf("@", 0) < 0)
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}

if (email.value.indexOf(".", 0) < 0)
{
    window.alert("Please enter a valid e-mail address.");
    email.focus();
    return false;
}

Multiple if statements have a cascading effect. If the first if statement indicates that the e-mail address contains a value, the second if statement runs, and if the second if statement indicates that the e-mail address contains an @ symbol, the third if statement runs. If any of the three if statements indicate an invalid e-mail address, a message is displayed to the user, the validation function returns false, and the user is returned to the form with the Insertion Point in the Email field.

You can also create a similar if statement for telephone numbers. If you specify the format for telephone numbers, you can use the indexOf method to determine whether a specified string (which in some cases is a hyphen [-]) occurs within the telephone form field. If the indexOf method returns a –1, the telephone number does not contain a hyphen.

Returning a Value from a Function

You can return a value from a custom function by using the return statement. As mentioned previously, each of the if statements shown previously contains a line that returns a Boolean value of false. When the validation function returns to the form, the return value tells the form whether to continue processing. A value of false tells the browser to stop processing the form. Therefore, at the end of the validation function, you also need a statement to return a value of true. This means that all form fields have validated and the form can continue processing.

Complete Form Validation Script

The following code sample shows the complete ValidateContactForm function for the contact form.

function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone;
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;

    if (name.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }
    
    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }

    if ((nocall.checked == false) && (phone.value == ""))
    {
        window.alert("Please enter your telephone number.");
        phone.focus();
        return false;
    }

    if (what.selectedIndex < 1)
    {
        alert("Please tell us how we can help you.");
        what.focus();
        return false;
    }

    if (comment.value == "")
    {
        window.alert("Please provide a detailed description or comment.");
        comment.focus();
        return false;
    }
    return true;
}

Code Sample 5. Complete ValidateContactForm function

Connecting the Form to the Script

After you write the validation function, you need to tell your form to run the script when someone clicks the Submit button. To do this, you need to use the onsubmit event for the form. For more information, see onsubmit Event. (The onsubmit event occurs every time a form is submitted for processing, but it happens on the client side, so if all processing is done on the server, you don't need the onsubmit event.)

To cause your validation script to run every time a user submits the contact form, add the following code to the opening <form> tag.

onsubmit="return ValidateContactForm();"

Now you are ready to display your form in a browser and test the script, which you can do by filling the form fields with invalid data and clicking the Submit button.

Associating Form Fields with Custom Script

Sometimes you may want to respond when users select certain fields. For example, when a user clicks a button or selects a check box, you may want to enable or disable another field, display a secondary form page, or just display a message. Events allow you to respond to such situations.

An event is something that occurs within the browser or something that occurs as a result of something that a user does. For example, the onload event occurs every time a page loads and the onclick event occurs every time a user clicks something contained within the page. For more information, see onload event and onclick event. Events enable the browser to perform a certain action when a specific action occurs.

You can respond to user events in two ways.

  • Add the event script inline within the opening tag for the element
  • Add the event to the element with a reference to a custom function

In the contact form is a check box named DoNotCall. When a user selects this check box, the browser disables the Telephone field so that the user cannot enter a value. The following sections show how to disable the Telephone field using both methods.

Using Inline Event Scripting

If the script is simple, you can easily add the script for the event inline with the element. Although you can add multiple commands to an inline script, placing longer script code into a custom function makes the function more readable and thus easy to debug, or find errors in the code.

The following code shows how to handle the onclick event for the DoNotCall check box field. In this code, if the check box is checked, the Telephone field is disabled.

onclick="if(this.checked==true){document.ContactForm.Telephone.disabled = true;}"

You can insert this into the DoNotCall field in your form to see how it functions. In this case, the inline code doesn't function well because if a user selects the check box and then clears it, the Telephone field never becomes enabled again. In this case, a longer script is required. The following section shows you how to create a custom function for the event.

Using an Event Handler Function

Creating a function in response to an event is the same as creating any other function. Instead of adding the event script to the event in the opening tag of the element, you add the name of the function that handles the event.

As shown in the previous section, you need the Telephone field disabled if the DoNotCall field is checked. But if the DoNotCall field is cleared, the Telephone field should be re-enabled. The following function shows how to do this using an if. . .else statement.

function EnableDisable(chkbx)
{
    if(chkbx.checked == true)
    {
        document.ContactForm.Telephone.disabled = true;
    }
    else
    {
        document.ContactForm.Telephone.disabled = false;
    }
}

After you created the custom function, you can add the following code tag for the DoNotCall field.

onclick="EnableDisable(this);"

Notice that the EnableDisable function takes an argument. Therefore, when you call the event from within the element, you need to pass a value. In this case, you need to pass the current element, and the easiest way to do so is to use the this statement. For more information, see this Statement.

Code Listing

The following listing shows the complete code for the example in this article.

<html>

<head>
<title>Form Validation Example</title>

<script>
function ValidateContactForm()
{
    var name = document.ContactForm.Name;
    var email = document.ContactForm.Email;
    var phone = document.ContactForm.Telephone;
    var nocall = document.ContactForm.DoNotCall;
    var what = document.ContactForm.Subject;
    var comment = document.ContactForm.Comment;

    if (name.value == "")
    {
        window.alert("Please enter your name.");
        name.focus();
        return false;
    }
    
    if (email.value == "")
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf("@", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }
    if (email.value.indexOf(".", 0) < 0)
    {
        window.alert("Please enter a valid e-mail address.");
        email.focus();
        return false;
    }

    if ((nocall.checked == false) && (phone.value == ""))
    {
        window.alert("Please enter your telephone number.");
        phone.focus();
        return false;
    }

    if (what.selectedIndex < 1)
    {
        alert("Please tell us how we can help you.");
        what.focus();
        return false;
    }

    if (comment.value == "")
    {
        window.alert("Please provide a detailed description or comment.");
        comment.focus();
        return false;
    }
    return true;
}

function EnableDisable(chkbx)
{
    if(chkbx.checked == true)
    {
        document.ContactForm.Telephone.disabled = true;
    }
    else
    {
        document.ContactForm.Telephone.disabled = false;
    }
}
</script>
</head>

<body>

<form method="post" action="mailto:Frank@cohowinery.com" 
name="ContactForm" onsubmit="return ValidateContactForm();">
    <p>Name: <input type="text" size="65" name="Name"></p>
    <p>E-mail Address:  <input type="text" size="65" name="Email"></p>
    <p>Telephone: <input type="text" size="65" name="Telephone"><br>
        <input type="checkbox" name="DoNotCall" 
        onclick="EnableDisable(this);"> Please do not call me.</p>
    <p>What can we help you with?
        <select type="text" value="" name="Subject">
            <option>  </option>
            <option>Customer Service</option>
            <option>Question</option>
            <option>Comment</option>
            <option>Consultation</option>
            <option>Other</option>
        </select></p>
    <p>Comments:  <textarea cols="55" name="Comment">  </textarea></p>
    <p><input type="submit" value="Send" name="submit">
    <input type="reset" value="Reset" name="reset"></p>
</form>

</body>
</html>

Conclusion

As you see, adding simple client-side validation to your forms by using JavaScript is relatively easy. You learned how to name your form fields and then access those fields in script. You also learned how to check for the values of form fields and return control back to the form to continue or stop processing. And finally, you learned how to associate form fields with custom scripts and to enable or disable certain fields based on the value of other fields.

If this was your first introduction to JavaScript, you may find one of the following resources from O'Reilly helpful for expanding your knowledge and understanding of JavaScript.

Show:
© 2016 Microsoft