Saylor Academy



CS412

Interactive JavaScript Lab

Introduction

As you have worked your way through the JavaScript material in the course, you have learned about basic JavaScript syntax and how to run JavaScript programs from within an HTML document. Perhaps one of the most powerful uses of JavaScript is validating forms before the information is sent to other pages or written to a database table. In this lab, we will first work through an example and then give you the opportunity to write your own code.

Pharmacy Order Form

Figure 1 shows a pharmacy order form. The HTML code for this can be found in the file named pharmacy order form part1.html. Click here to view the code, which is also displayed in Figure 2.

[pic]

Figure 1

[pic]

Figure 2

In order to help us to write the validation, let’s create a table of all of the input fields on the form.

|Field Name |Type |Validation Required |

|customerName |Text |Check to make sure that it is filled in. |

|address |Text |Check to make sure that it is filled in. |

|city |Text—only letters |Check to make sure that it is filled in. |

|state |Text |Check to make sure that a state has been |

| | |selected from the dropdown list. |

|zip |Text—numbers only |Check to make sure that it has been filled in |

| | |and that the formatting is correct. We should |

| | |check for zip+5. |

Validation Methods

There are a couple of ways to call JavaScript validation functions from a form. One method is to write individual functions for each field that will be executed when the user moves from the field to another field. While this method does work fine, I prefer to use a validation that runs when the user presses the submit button. If your form is going to redirect the user to another form, the submit validation will not allow the redirection unless all validations are correct.

Let’s start by writing some JavaScript code to validate the name. As you may recall from the course, all JavaScript code is written inside the head of the HTML form. Figure 3 shows a simple function to validate the name.

[pic]

Figure 3

I’m only showing the JavaScript code as well as a little bit of code to call the function. The HTML code for the form is the same as Figure 2. Let’s look at the function. Notice that line 5 has a parameter frm. This is the actual form itself. If you look at line 15, you will see that we pass this into the function. This refers to the form object. Line 7 checks to make sure that at least one character was entered in customerName. Line 8 is simply an alert, which pops a message onto the screen.

In line 15, the function is called as part of the onSubmit event. Once the submit button has been pressed, the validation is completed.

Let’s go ahead and add some additional validation for address and city, which will be the same as the customerName validation. We will also add a validation for state, which is a bit different. Figure 4 shows the code including address, city, and state validations.

[pic]

Figure 4

There is not much different here until line 18, where we will check to make sure that a value has been selected for state from the dropdown listbox. Since it is possible for the user to select no state, we need to check to make sure that state has been entered. We do this by simply checking the value.

Regular Expressions

Before we look at the zip code validation, let’s talk a bit about regular expressions. You may have already used these in other programming that you have done. Regular expressions (or REGEX) are powerful, since they allow you to quickly check to see whether a field contains certain characters.

In JavaScript, regular expressions can be written two ways: with a regex object when you want to create the expression string dynamically and with a string literal. We will mostly use the second method. A string literal is usually defined between two backslashes or inside parentheses.

A good site to go to if you would like to look up some common regular expressions is . There is also a utility available there to allow you to test your regular expressions. Let’s look at an example to check to make sure that we have entered only letters for the name:

var regex = “^[a-zA-Z]+$”

if (frm.customerName.value.search(regex) == -1)

alert(“Letters only please!”)

The first line defines the regular expression, which can be thought of as a template to check to see what the string is made up of. The variable regex is a string itself. The ^ symbol tells the regular expression evaluator to start matching characters at the beginning of the string. Anything inside the parentheses defines that portion of the match. The brackets define what to look for. In this case, [A-Za-z] indicates that we should be looking for only uppercase letters between A and Z or lowercase letters between a and z. The + specifies that one or more of the preceding characters must match. The $ indicates that we should also check the end of the string.

Within the if statement, we use the search method of a string field to check to see if the regular expression is found. If this returns a -1, then the expression was not found and an alert is displayed on the screen. You can view and run the complete code here. Try running this in a browser. What happens if you enter a name like Samuel L. Morris?

You may have noticed that the regular expression only checks for uppercase and lowercase letters. The example above (Samuel L. Morris) contains some spaces and a period. We can check for this by changing our regular expression slightly.

var regex = "^[a-zA-Z0-9\.\ ]+$"

Notice that we have added \. and \ to the regular expression. We need to precede the period as well as the space with a backslash (\) in order to indicate that these should be interpreted literally and not as special characters. You can test the modified HTML file here.

Checking for Numeric Characters

Now, let’s take a look at the regular expression that we need for the zip code. If we follow U.S. zip code rules, then the characters have to be all numbers. Generally, there are five digits with a – and then four more digits. The – and four additional digits are optional. Let’s take a look at the code for this:

var regex="^([0-9]{5}(-[0-9]{4})?)$"; //regular expression defining a 5 digitnumber

if (frm.zip.value.search(regex)==-1) //if match failed

alert("Please enter a valid zipcode")

}

Let’s look at the regular expression. As we have seen before, the ^ indicates that we should search at the start of the string. The [0-9] indicates that we should only validate numbers. The {5} is a quantifier that specifies that the previous character repeats exactly five times. So, we are looking for five numbers between 0 and 9. The next part of the expression is inside of its own parentheses. This is because the ? that follows it will apply to only the last part of the expression. So, for example, a user could enter 45332 and this would be OK, since ? indicates that there the preceding characters are optional. If we did not have the parentheses, then a user could enter no zip code and it still would validate. Getting back to the next expression, the – indicates a possible range of characters. The [0-9]{4} is similar to what we had seen in the first part of the expression, four characters all in the range 0–9. You can view and run the code for this here.

Validating without Clearing the Form

You may have noticed in our examples that the form was cleared whenever there was an invalid validation. So, for example, if you entered everything correctly except for the zip code, you would have to rewrite everything. One way around this is to stop the validation whenever an error occurs and set the focus back to the control (textarea, etc.) Figure 5 shows the rewrite of a portion of our example in order to enable this. We will discuss this below. You can also download the code to test here. It is named pharmacy order form part 2 with return.html.

[pic]

Figure 5

Let’s take a look at lines 9–11. Since we want to return the user to the field where the data entry error occurred, we need to use the focus method. However, we cannot directly reference the element by name. Instead, we need to get the element by name using a JavaScript function. Once we have done this, we are setting the focus (where the cursor lands) to the field. Finally, line 11 returns a value of false. This will do two things: If we were going to move to another page or PHP script after the submit button was pressed, the false value will not allow this. Also, any other fields will not be cleared so that we can simply fix one little mistake.

Additional Validation with Regular Expressions

You have noticed that you can enter any value into city. Let’s fix this by only allowing letters in the city and also making sure that the first letter of the city starts with an uppercase letter.

var regex = "^[A-Z]+[a-z\ ]+";

if (frm.city.value.search(regex) == -1)

{

alert("You must enter a valid city!");

var item=document.getElementsByName("city")[0];

item.focus();

return false;

}

Let’s take a quick look at the regular expression. Notice how the first character has to be an uppercase character (the + after the [A-Z] indicates this) and we have to have at least one lowercase letter. You can view the code for this here.

Exercise

You can find solutions to this exercise in the solutions document.

Code for a form that renders similar to Figure 6 is shown in Figure 7 and can be found here.

[pic]

Figure 6

Henry's Pet Store Order Form

Name:

Address:

City:

State:

Choose a state

AK

AL

AR

AZ

CA

CO

CT

DC

DE

FL

GA

HI

IA

ID

IL

IN

KS

KY

LA

MA

MD

ME

MI

MN

MO

MS

MT

NC

ND

NE

NH

NJ

NM

NV

NY

OH

OK

OR

PA

RI

SC

SD

TN

TX

UT

VA

VT

WA

WI

WV

WY

AA

AE

AP

AS

FM

GU

MP

MH

PR

PW

VI

  Zip:

Telephone Number:

Dry Dog Food (Quantity)

Soft Dog Food Quantity

Cat Food Quantity

Figure 7

Write JavaScript code to validate this form according to the following rules:

1. Name must contain all letters.

2. City must contain all letters and the first letter must be capitalized.

3. A state must have been chosen.

4. Zip code must be either five digits, or five digits, a dash, and four digits.

5. Telephone number must be in the following format:

(999) 999-9999

You may want to check out a few regular expression sites for some hints.

6. All the quantities of food entered must be between 0 and 50.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download