9. Forms and Validation

What We Will Cover


Elucidations

Questions from last class?

Homework Questions?

Homework Discussion Questions

  1. How important is navigation in Web design?
  2. What are some situations in which bad Web design has made navigation unpleasant or confusing?
  3. Some Web programmers like simplicity while others like to use many effects in the Web sites they design. Effects, if used appropriately, improve the user experience, making the site more user-friendly and appealing to the eye. But using too many effects looks or using them inappropriately seems unprofessional and may actually confuse the users. What are advantages and disadvantages of using effects in Web pages?

9.1: Working with Forms and Fields

Learner Outcomes

At the end of the lesson the student will be able to:

  • Reference form element objects
  • Apply and remove focus on a form field

9.1.1: About Forms and Form Validation

  • In this lesson we work with forms and form validation
  • First we learn how to reference form element objects and how to extract data from them
  • Also, we learn how to create a calculated form field and how to format numeric values
  • Then we explore the principles of form validation and learn how to perform a client-side validation
  • To do this, we mostly work with strings
  • Later on, we will work with regular expressions as well
    • A regular expression is a technique for finding patterns in strings
    • A simple example is a DOS/Windows wildcard like: *.html
    • This expression means all file names ending with html
    • JavaScript allows you to match and manipulate more complex patterns
    • Later, we will explore how to create these patterns and how to use them

Case Study: GPS-ware Shopping Cart

  • To help us learn, the textbook presents a case study on page JVS 335
  • We will work with three linked web pages during this lesson:
  • Our job is to validate the data a user enters and automatically calculate the cost of an order
  • The plan is to verify the data and perform the calculations before submitting the data to the Web server
  • You can see a description of the first form and its fields in the following diagram

GPS-ware Order Form

Form fields

9.1.2: Referencing a Web Form

  • You have to work with the properties and methods of the form object and the elements it contains
  • Web forms are part of the hierarchy of objects in the Web page like the one shown in the following diagram

Forms Hierarchy

Form objects

Selecting the Form

  • Since a Web page can have multiple forms, you first need to select the form you are working with
  • You can access a form using the document reference:
    document.forms[idref]
    
  • Where idref is the id or index number of the form
  • Another way is to use the name of the form:
    document.fname
    
  • In our case study, the name of the form on the GPS-ware Order Form page is: form1
  • Also, the id of the form is: form1
  • In addition, the page has only one form
  • Thus, we can access the form in several ways including:
    document.forms[0]
    document.forms["form1"]
    document.form1
    

9.1.3: Referencing a Form Element

  • The elements within a form are organized into an elements collection
  • You can reference a form element either by its position in the collection or by its name or id attributes
  • For example, to reference the first element in the order form:
    document.form1.elements[0]
    or
    document.form1.date
  • The following chart shows the object references for the elements of the order form

Objects in the Order Form

Form elements in the order form

9.1.4: Setting a Field Value

  • To set the value contained in a field such as an input box, you use the value property
  • Syntax:
    formObject.element.value = fieldValue;
    
  • For example:
    document.form1.date.value = "11-13-2006";
    
  • Note that an input field has many properties and methods
  • Some of these are shown in the charts in the textbook on page JVS 341

9.1.5: Navigating Between Fields

  • Often times you want certain fields of a form to be selected automatically
  • For instance, for our case study we want the product selection list to be selected when the page opens
  • For this we can use the focus and blur events
  • The focus event places the cursor in a particular field of a form
  • Syntax:
    formObject.element.focus();
  • The blur event removes the focus from the field
  • Syntax:
    formObject.element.blur();
  • Thus, to put the focus on the product selection list you can use:
    document.form1.prod.focus();
  • We can put this into a function that gets called when the page opens, like:
    function startForm() {
        document.form1.date.value = todayTxt();
        document.form1.prod.focus();
    }
    
  • Then we add the event handler onload="startForm()" to the body element
    <body onload="startForm();">

9.1.6: Summary

  • In this section we looked at how to reference form element objects and how to extract data from them
  • You can access a form using the document reference:
    document.forms[idref]
    
  • Where idref is the id or index number of the form
  • Another way is to use the name of the form:
    document.fname
    
  • The elements within a form are organized into an elements collection
  • You can reference a form element either by its position in the collection or by its name or id attributes
  • You can set the value of a field using the syntax:
    formObject.element.value = fieldValue;
    
  • In addition, we looked at how to set the focus using the syntax:
    formObject.element.focus();
  • Also you can remove the focus using:
    formObject.element.blur();

More Form Element Information

Check Yourself

  1. How do you specify the object reference to the second Web form in a document?
  2. How do you specify the object reference to the lastname input field found in a web form named "register"?
  3. What statement would change the value of the lastname field to "Parrish"?
  4. What statement would move the cursor to the lastname field?

Activity 9.1

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. Which of the following is NOT a way to select the first element (named first) of the first form (named form1) on a page?
    1. document.form1.first
    2. document.forms[0].first
    3. document.forms[0].elements[0]
    4. document.forms[0].first[0]

  2. The event occurs when a user's cursor moves to the field.
  3. The away event occurs when the cursor moves away from the field.

    True
    False

  4. When would you want to use the focus() method?

9.2: More About Working With Forms

Learner Outcomes

At the end of the lesson the student will be able to:

  • Extract data from input fields, selection lists, and radio button groups
  • Create a calculated field
  • Format currency fields rounded to two decimal places

9.2.1: Working with Selection Lists

  • The GPS-ware Order Form uses a selection list for products and prices
  • This was done so customers select only valid products and prices
  • Here is the product list:

  • Which is generate by this HTML code:
<select name="prod" id="prod">
<option value="0">Products from GPS-ware</option>
<option value="19.95">GoMap 1.0 ($19.95)</option>
<option value="29.95">Drive Planner 2.0 ($29.95)</option>
<option value="29.95">Hiker 1.0 ($29.95)</option>
<option value="149.50">G-Receiver I ($149.50)</option>
<option value="199.50">G-Receiver II ($199.50)</option>
<option value="249.50">G-Receiver III ($249.50)</option>
</select>
  • Unlike a text field, there is no value property for the entire list
  • Instead, the HTML DOM organizes all the options as a collection
  • To reference a particular option in the collection, you use the syntax:
    element.options[idref]
  • Where element is a reference to the list and idref is the index number or id of the option
  • Each option in the select list has text and value properties
  • You can see these properties in the table below

Properties in the products Selection List

object object.text object.value
document.form1.prod.options[0] Products from GPS-ware 0
document.form1.prod.options[1] GoMap 1.0 ($19.95) 19.95
document.form1.prod.options[2] Drive Planner 2.0 ($29.95) 29.95
document.form1.prod.options[3] Hiker 1.0 ($29.95) 29.95
document.form1.prod.options[4] G-Receiver I ($149.50) 149.50
document.form1.prod.options[5] G-Receiver II ($199.50) 199.5
document.form1.prod.options[6] G-Receiver III ($249.50) 249.50

Finding the Option

  • Since we know the values for each option, we can find the value for the option the customer chose if we know the index
  • We can get the index selected by using the selectedIndex property of the selection list
  • Syntax:
    element.selectedIndex
  • Where element is the selection list element in the page
  • For example, to get the price from the order form, we could use code like:
    product = document.form1.prod;
    prodIndex = product.selectedIndex;
    prodPrice = product.options[prodIndex].value;
    
  • Note that if a selection lists allows multiple selections, the selectedIndex property returns only the index of the first item selected
  • If you want to check if multiple items are selected, you loop through the options collection and test the selected property of each option

More Selection List and Options Properties

9.2.2: Calculating the Total Price

  • We can use our knowledge of selection lists to calculate the total price of a product
  • The total price is the cost per item times the quantity ordered:
    totalPrice = prodPrice * qtyOrdered
  • We want to perform this calculation and display the total price in the order form
  • For this, we write the function calcPrice() shown below
  • Whenever the customer changes the produce or the quantity, we call this function
  • To call the function, for both selection lists we set the onchange event handler
    onchange="calcPrice()"

Function calcPrice()

calcPrice() function

9.2.3: Working with Radio Buttons and Check Boxes

  • Our next task is to display shipping costs for the selected product
  • The GPS-ware Order Form has the shipping options within a group of radio buttons
  • The HTML DOM places all the radio buttons of a group into an array
  • To access a single button, you use the syntax:
    element[idref]
  • Where element is the reference to the group of option buttons and idref is either the index number or id of the individual option button
  • For example, in the order form, we could select the first shipType radio button using either:
    document.form1.shipType[0];
    document.form1.shipType["ship1"];
    
  • Another way to access an individual button is: document.getElementById()

Getting the Button Value

  • Radio buttons have several properties as shown on page JVS 347 of the textbook
  • Also, you can view the properties at: HTML DOM Radio Object
  • One of the useful properties is checked
  • The checked property indicates whether the radio button is checked or not
  • Another of the properties is value, which has the value associated with the button
  • Thus, to extract the value of the first radio button, we could use code like:
    document.form1.shipType[0].value

Check Boxes

  • Check boxes work like a radio button
  • A check box supports the checked property indicating whether the check box is checked or not
  • Also, you can use the value property to get the value of the check box
  • However, the value is supplied only when the check box is checked
  • When unchecked, the value property has no value assigned to it

9.2.4: Calculating the Shipping

  • Let us look at how to calculate the cost of shipping
  • We could use a loop to search through all the radio buttons to see which one is checked
  • However, there is an easier and more elegant way using the this keyword

Using the this Keyword

  • The this keyword refers to the currently selected object
  • The this keyword is useful when a function might work with several objects and you want to work with the object that called the function
  • To use this technique, we create a function with an object parameter:
    function calcShipping(shipOption) {
        document.form1.ship.value = shipOption.value;
    }
    
  • Then we use the this keyword when we call the function:
    onclick="calcShipping(this)"
  • Since the current object is the radio button that the user clicks, we can simplify our code by passing this as a parameter

9.2.5: Creating Calculated Fields

  • To complete the order form, we need to calculate the remaining values:
    • subtotal: product price plus shipping cost
    • sales tax
    • total cost: subtotal plus sales tax
  • One complication is that JavaScript treats the contents of input fields as strings
  • This means that the + operator concatenates the strings rather than summing them
  • To perform the addition, we need to convert the strings to numbers
  • We have done this before using the parseFloat() method
  • Thus, we can create the calcTotal() function shown below
  • Also, we can use the event handlers we already created by adding a call to calcTotal() to the calcPrice() and calcShipping() functions

Adding the calcTotal() Function

calcTotal() function

9.2.6: Formatting Numbers

  • One remaining problem is the formatting of the numbers
  • All of the currency fields need to be displayed as dollars and cents rounded to two decimal places
  • An easy way to do this is with the toFixed() method introduced in JavaScript 1.5
  • For example, in the calcTotal() function we can change these lines:

    document.form1.sub.value = subtotal.toFixed(2);
    document.form1.tax.value = taxVal.toFixed(2);
    document.form1.tot.value = (subtotal + taxVal).toFixed(2);

Working with Older Browsers

  • Note that the toFixed() method was introduced in JavaScript 1.5
  • This means that it is not supported in browsers earlier than IE 5.5, Netscape 6.0 and Opera 6.02
  • To work with these browsers, we need to use methods available in earlier versions of JavaScript
  • The textbook supplier us with a toFixed2() function we can use instead
  • This function makes use of a roundValue() function in its computation
  • Both of these functions are part of the functions.js file supplied with the case study
  • Here are some examples using this function:

    document.form1.sub.value = toFixed2(subtotal);
    document.form1.tax.value = toFixed2(taxVal);
    document.form1.tot.value = toFixed2(subtotal + taxVal);

9.2.7: Summary

  • In this section, we continued to explore how to reference different elements in a Web form
  • First we looked at the selection list, which uses the syntax:
    element.options[idref]
  • Where element is a reference to the list and idref is the index number or id of the option
  • Each option in the select list has text and value properties that you can access
  • You can find the index selected by using the selectedIndex property of the selection list using the syntax:
    element.selectedIndex
  • If a selection lists allows multiple selections, the selectedIndex property returns only the index of the first item selected
  • Next we looked accessing a radio button, which has the syntax:
    element[idref]
  • Where element is the reference to the group of option buttons and idref is either the index number or id of the individual option button
  • To get the value of a particular radio button, you can use the value property
  • Check boxes work like a radio button
  • A check box supports the checked property indicating whether the check box is checked or not
  • Also, you can use the value property to get the value of the check box
  • However, the value is supplied only when the check box is checked
  • In addition, we looked at an example using the this keyword
  • The this keyword refers to the currently selected object
  • We called a function using the this keyword as an argument for an event handler
    onclick="calcShipping(this)"
  • Finally, we looked at formatting numeric values rounded to two decimal places using the toFixed() method
  • However, the toFixed() method was introduced in JavaScript 1.5
  • This means that it is not supported in browsers earlier than IE 5.5, Netscape 6.0 and Opera 6.02
  • To work with these browsers, we looked at a custom function that used methods available in earlier versions of JavaScript

Check Yourself

  1. What is the code to specify the object reference to the fourth option in the statename selection list? Assume that the name of the form is billinginfo.
  2. What expression would return the index number of the selected option from the statename selection list?
  3. What expression would indicate whether the contactme check box field in the billinginfo form is selected?
  4. What code would you use to convert the number 3.14159 to a text string displaying the value rounded to two decimal places?

Activity 9.2

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. Which of the following objects has a selectedIndex property?
    1. Selection list
    2. Option object
    3. Radio button
    4. Check box

  2. If a selection list is set up to collect multiple selections, the selectedIndex property returns the index number of the selected item.
  3. The parseFloat() function extracts the first numeric value from a text string.

    True
    False

  4. Have you programmed in Java or C++ before? If so, how does the use of the "this" keyword differ from its use in JavaScript?

9.3: Working with Form Validation

Learner Outcomes

At the end of the lesson the student will be able to:

  • Discuss the principles of form validation
  • Perform a client-side validation
  • Work with the properties and methods of string objects

9.3.1: About Form Validation

  • Form validation is the process of checking a form for data entry errors
  • There are two types of form validation: server-side validation and client-side validation
  • With server-side validation, a form is sent to the Web server for checking
  • In client-side validation, the Web browser checks the form, which is not submitted to the server until it passes inspection
  • Diagrams of these are shown on page JVS 355 of the textbook

Implementing Form Validation

  • Professionally, you want to use both forms of validation
  • Client-side validation requires less processing by the server
  • Also, feedback is much quicker because there is no network lag
  • However, client-side validation is not foolproof
  • Some browsers do not support JavaScript
    • Or the user has disabled JavaScript
  • Thus, you always want the server to perform a final check of the data
  • Note that server-side validation is beyond the scope of this course
  • You can take CIS-165PH to learn server-side validation with PHP

9.3.2: Submitting a Form and Checking the Data

  • Generally, you validate form data when the user submits the form
  • By default, the browser takes the action specified by the action attribute
  • For example, the GPS-ware Order Form goes to the next form page
    action="form2.htm"
  • To check forms when submitted, we need to take control of the submission process
  • To control the submission process, JavaScript provides the onsubmit event handler
    <form onsubmit="return function()"> ... </form>
    
  • If the function returns a value of false, the submit event is canceled
  • Otherwise, a value of true allows the submit event to continue
  • We can create a function for our order form to verify the user selects something for all three input areas
  • You can see this function (from the textbook page JVS 356) listed below
  • To enable the function, you add an event handler to the form element:
    onsubmit="return checkForm1()"
  • To see the validation function in action: click here

Function checkForm1()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function checkForm1() {
    if (document.form1.prod.selectedIndex == 0) {
        alert("You must select a GPS-ware product");
        return false;
    } else if (document.form1.qty.selectedIndex == 0) {
        alert("You must select a quantity to order");
        return false;
    } else if (document.form1.ship.value == "0.00") {
        alert("You must select a shipping option");
        return false;
    } else {
        return true;
    }
}

9.3.3: Resetting a Form

  • Clicking the reset button normally resets all form fields to their default values
  • In our GPS-ware Order Form example, the reset button is labeled, "Cancel"
  • If you press the "Cancel" button, you will notice that the current date does not reset correctly
  • To make this work right, we need to both reset the form fields and call the startForm() function when the user presses the "Cancel" button
  • You can control how the reset event is handled by adding an onreset event handler
  • To both reset the form fields and call the startForm() function, we can use the location.reload() method
  • Thus, our onreset event handler becomes:
    onreset="location.reload()"
  • To see the onreset event handler in action: click here

9.3.4: Working with Text Strings

  • Sometimes you need to work with form values as text strings
  • For instance, in the second form of our case study, we want to check that a customer enters:
    1. A value in all the fields
    2. An optional zip code that is five digits long with no non-numeric characters

The String Object

  • To work with strings in JavaScript, you use the String object
  • JavaScript treats each text string as an object called a string object
  • The most common way to create a string object is to assign a text string to a variable:
    stringVariable = "text";
  • You can also create a string object using the object constructor:
    stringVariable = new String("text");
  • With the second technique, you can be certain you are working with a string object rather than relying on an implicit conversion

Calculating the Length of a Text String

  • One of the properties of a string object is length
  • The length property returns the number of characters in a string
  • For example:
    <script type="text/javascript">
        var message = "JavaScript rules!";
        document.write(message.length);
    </script>
    
  • Produces the output:

  • We can use the length property to validate that a customer has entered a value in all the fields
  • Also, we can verify that if a zip code is entered, it is five characters in length
  • You can see a listing of these validation functions below
  • To see the validation functions in action: click here

Function checkForm2()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
function checkForm2() {
    if (document.form2.fname.value.length == 0) {
        alert("You must enter a first name");
        return false;
    } else if (document.form2.lname.value.length == 0) {
        alert("You must enter a last name");
        return false;
    } else if (document.form2.street.value.length == 0) {
        alert("You must enter a street address");
        return false;
    } else if (document.form2.city.value.length == 0) {
        alert("You must enter a city name");
        return false;
    } else if (checkZip(document.form2.zip.value) == false) {
        alert("You must enter a valid zip code");
        return false;
    }
    return true;
}

function checkZip(zip) {
    if (zip.length != 0 && zip.length != 5) {
        return false;
    }
    return true;
}

9.3.5: Working with the String Object Methods

  • Our checkZip() function verifies the length but not whether all the characters are digits
  • To make sure all the characters are valid, we can use various methods of the String object
  • Several of these methods are listed in the textbook on pages JVS 365 and 368
  • Also, you can view the methods of the string object here

Accessing Characters with charAt()

  • JavaScript lets you access the individual characters of a string
  • Syntax:
    string.charAt(index)
  • Where string is the string object and index is the location in the string
  • The first character is at index 0 and the last is one less than the length of the string
  • The charAt() method lets you work with the string like it was an array
  • Thus, we can use a loop to access every character of a string
  • For example:
    <script type="text/javascript">
        var zip = "95003";
        for (i = 0; i < zip.length; i++) {
            zipchar = zip.charAt(i);
            document.write(zipchar + "<br />");
        }
    </script>
    
  • Produces the output:

  • For more information see: Core JavaScript 1.5 Reference:Global Objects:String:charAt

Finding Characters with indexOf()

  • Another method lets you search for the first occurrence of a letter in a string
  • Syntax:
    string.indexOf(substr, start)
    
  • Where string is the string object and substr is the substring you are looking for
  • The start parameter is optional and specifies the first character position to start the search
  • If you do not specify a start position, then the search starts at 0
  • The method returns the index of the substring you are searching for
  • For example:
    <script type="text/javascript">
        var numbers = "0123456789";
        var index = numbers.indexOf("123");
        document.write(index);
    </script>
    
  • Produces the output:

  • For more information see: Core JavaScript 1.5 Reference:Global Objects:String:indexOf

Function checkZip()

  • With these string methods, we can improve our checkzip() function
  • We can verify that every character is a digit as shown below
  • To see the improved checkzip() function in action: click here
1
2
3
4
5
6
7
8
9
10
11
12
13
14
function checkZip(zip) {
    if (zip.length != 0 && zip.length != 5) {
        return false;
    } else {
        validchars = "0123456789";
        for (i = 0; i < zip.length; i++) {
            zipchar = zip.charAt(i);
            if (validchars.indexOf(zipchar) == -1) {
                return false;
            }
        }
    }
    return true;
}

9.3.6: Summary

  • Form validation is the process of checking a form for data entry errors
  • There are two types of form validation: server-side validation and client-side validation
  • We started this section comparing the benefits and costs of both types of form validation
  • Then we looked at how to validate a form before allowing the server to process it
  • In addition, we looked at the properties and methods of the string object
  • We applied these properties and methods to validating zip codes

Tips for Validating Forms

  • Use selection lists, option buttons, and check boxes to limit the ability of users to enter erroneous data
  • Indicate to users which fields are required, and if possible, indicate the format that each field value should be entered in
  • Format financial values using the toFixed() and toPrecision() methods. For older browsers use custom scripts to format financial data
  • Use the maxlength attribute of the input element to limit the length of text entered into a form field
  • Apply client-side validation checks to lessen the load of the server
  • Use the length property of the string object to test whether the user has entered a value in a required field

Check Yourself

  1. Refer to page JVS 368 and 369 of the textbook and review the Session 7.2 Quick Check questions.

Activity 9.3

Take one minute to read over the following Quick Quiz questions. We will discuss the questions in one minute.

Quick Quiz

  1. If you validate form data using JavaScript you no longer need to validate form data on the server.

    True
    False

  2. The method location.reload()
    1. Loads the document at the specified URL
    2. Reloads the document from the current URL
    3. Returns true if a specified URL is reloaded
    4. None of these

  3. JavaScript treats each text string as an object called a object.

Wrap Up

Due Next:
A9: Form Validation (11/6/06)
Discussion 8 and Quiz 8 (11/6/06)

Home | WebCT | Announcements | Schedule | Room Policies | Course Info
Help | FAQ's | HowTo's | Links

Last Updated: November 18 2006 @17:39:51