Chapter 16
Chapter 16
Using JavaScript and Forms
JavaScript wears many hats. You can use it to create special effects. You can use it to make your HTML pages "smarter" by using its decision-making capabilities. And you can use it to enhance HTML forms. This last application is of particular important and merit. Of all the hats JavaScript can wear, its form processing features are among the most sought and used.
Without JavaScript, forms are pretty much the domain of CGI programs and scripts. You use HTML to create the form, but the form itself is accepted and processed by some program running on the computer. With JavaScript you can process simple forms without invoking the server. And when submitting the form to a CGI program is necessary, you can have JavaScript take care of all the preliminary requirements, like validating input to ensure that the user has dotted every i.
Using JavaScript with forms is of such important that there are two chapters on this topic: the one
you're reading now, and Chapter 18, "Using CGI with JavaScript." This chapter details how to
interface a form created with standard HTML tags with JavaScript, and how to perform tasks
such as input validation. Chapter 18 is devoted to the CGI side of things, linking a JavaScript-enhanced form to a CGI program or script that runs on the server.
Creating the Form
There are few differences between a straight HTML form and a JavaScript-enhanced form. The main difference is that a JavaScript form relies on one or more "on..." event handlers. These invoke a JavaScript action when the user does something in the form, like clicks a button. The "on..." event handlers, which are placed with the rest of the attributes in the <FORM> tags, are invisible to a browser that don't support JavaScript. Because of this you can often use one form for both JavaScript and non-JavaScript browsers (though I don't necessarily recommend this on a support standpoint; you are usually better off creating two different forms).
Typical form objects include the following (I call them objects rather than the oft-used "widgets," because that's how JavaScript treats them):
- Text box for entering a line of text
- Push button for selecting an action
- Radio buttons for making one selection among a group of options
- Check boxes for selecting or deselecting a single, independent option
I won't bother enumerating all the attributes of these elements, and how to use them in HTML. Most any reference on HTML will provide you with the details (if you need a review, I include a summary of most all HTML 2.0 and Netscape-supported HTML 3.0 tags in Chapter 22, "All About HTML").
For use with JavaScript, you should always remember to provide a name for the form itself, and each element (object) you use. The names allow you to reference the object in your JavaScript program.
The typical form looks like this. Notice I've provided NAME= attributes for all form objects, including the form itself (which is also treated as a JavaScript object):
<FORM NAME="myform" ACTION="" METHOD="GET"> Enter something in the box:<BR> <INPUT TYPE="text" NAME="inputbox" VALUE=""><P> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)"> </FORM>
- FORM NAME="myform" defines and names the form. Elsewhere in the JavaScript you can reference this form by the name myform. The name you give your form is up to you, but it should comply with JavaScript's standard variable/function naming rules (no spaces, no weird characters except the underscore, etc.).
- ACTION="" defines how you want the browser to handle the form when it is submitted to a CGI program running on the server. As this form is not designed to submit anything, the typical URL for the CGI program is omitted.
- METHOD="GET" defines the method data is passed to the server when the form is submitted. As this form is not going to submit anything, in this case the attribute is actually wasted puffery. It's shown here for example purposes.
- INPUT TYPE="text" defines the text box object. This is standard HTML markup here.
- INPUT TYPE="button" defines the button object. This is standard HTML markup except for the onClick handler.
- onClick="testResults(this.form)" is called an event handler -- it handles an event, in this case clicking the button. When the button is clicked, JavaScript executes the expression within the quotes. The expression says to call the testResults function elsewhere in the script, and pass to it the current form object (accomplished with the this.form parameter).
Getting a Value from a Form Object
Here's the full script you can try as you experiment obtaining values from form objects. Load the page, then type something into the text box. Click the button, and what you typed is shown in the alert box. The output of this script is shown in Figure 16-1.
testform.html <CD> <HTML> <HEAD> <TITLE>Test Input </TITLE> <SCRIPT LANGUAGE="JavaScript"> function testResults (form) { var TestVar = form.inputbox.value; alert ("You typed: " + TestVar); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform" ACTION="" METHOD="GET"> Enter something in the box:<BR> <INPUT TYPE="text" NAME="inputbox" VALUE=""><P> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)"> </FORM> </BODY> </HTML>
<Figure 16.1. The form test input script.>
Here's how it works: You already know what happens when you click the button, from the paragraphs above: JavaScript calls the testResults function. The testResults function is passed the form object. I've given this object the name form inside the testResult function, but you can name this object anything you like.
This bears repeating in slightly different terms: the onClick="testResults(this.form)" passes the current form to the testResults function. In the testResults function this object goes by the name form. You do not use "this.form" within the testResults function, because JavaScript won't know what the "this" belongs to.
The function is simple -- it merely copies the contents of the text box to a variable named TestVar. Notice how the text box contents was referenced. I defined the form object I wanted to use (called form), the object within the form that I wanted to use (called inputbox), and the property of that object I wanted (the value property).
var TestVar = form.inputbox.value;Strictly speaking you don't have to pass the form object to a function in order to use that object within the function. Because the form is named you can reference it explicitly as a member of the document object. The following expression does the same thing as the one above: var TestVar = document.myform.inputbox.value; Here's how it breaks down, going from right to left: value is a property of the inputbox form control. inputbox is a member of the myform form object myform is a member of the current document.
Setting a Value in a Form Object
The value property of the inputbox, shown in the above example, is both readable and writable. That is, you can read whatever somebody types into the box, and you can write data back into it. The process of setting the value in a form object is just the reverse of reading it. Here's a short example to demonstrate. It's pretty much the same as the previous example, except this time there are two buttons, and the buttons have been relabeled. Click the "Read" button and the script reads what you typed into the text box. Click the "Write" button and the script writes a particularly lurid phrase into the text box.
set_formval.html <CD> <HTML> <HEAD> <TITLE>Test Input </TITLE> <SCRIPT LANGUAGE="JavaScript"> function readText (form) { TestVar =form.inputbox.value; alert ("You typed: " + TestVar); } function writeText (form) { form.inputbox.value = "Have a nice day!" } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform" ACTION="" METHOD="GET"> Enter something in the box:<BR> <INPUT TYPE="text" NAME="inputbox" VALUE=""><P> <INPUT TYPE="button" NAME="button1" Value="Read" onClick="readText(this.form)"> <INPUT TYPE="button" NAME="button2" Value="Write" onClick="writeText(this.form)"> </FORM> </BODY> </HTML>
- When you click the "Read" button, JavaScript calls the readText function, which reads and displays the value you entered into the text box.
- When you click the "Write" button, JavaScript calls the writeText function, which writes (yuk) "Have a nice day!" in the text box.
Reading Other Form Object Values
The text box is perhaps the most common form object you'll read (or write) using JavaScript. However, you can use JavaScript to read and write values these form objects as well :
- Hidden text box (TYPE="hidden").
- Radio button (TYPE="radio")
- Check box (TYPE="checkbox")
- Text area (<TEXT AREA>)
- Lists (<SELECT>)
Using Hidden Text Boxes
From a JavaScript standpoint, hidden text boxes behave just like regular text boxes, sharing the same properties and methods. From a user standpoint, hidden text boxes "don't exist" because they do not appear in the form. Rather, hidden text boxes are the means by which special information can be passed between server and client. They can also be used to hold temporary data that you might want to use later.
For server/client communications, the server can send data to the client, storing a special value in a hidden field that the user doesn't see. For example, the value might be the number of times the user has submitted a form in the same session. If it's more than say, five times, the server knows not to accept any more entries from that user. The submission count is stored in a hidden field.
Hidden fields are particularly handy for storing temporary data that your JavaScript program may
need. Store the data in a hidden field, and it stays as long as the document remains loaded.
(However, note that the contents of hidden fields are lost when a document or frame is reloaded
or resized.)
Using Radio Buttons
Radio buttons are used to allow the user to select one, and only one, item from a group of options. Radio buttons are always used in multiples; there is no logical sense in having just one radio button on a form, because once you click on it, you can't unclick it. If you want a simple click/unclick choice use a check box instead (see below).
To define radio buttons for JavaScript, provide each object with the same name. JavaScript will create an array of buttons out of them; you then reference the buttons using the array indexes. The first button in the series is numbered 0, the second is numbered 1, and so forth. Note that the VALUE attribute is optional for JavaScript-only forms. You'll want to provide a value if you submit the form to a CGI program running on the server, however.
<INPUT TYPE="radio" NAME="rad" VALUE="radio_button1" onClick=0> <INPUT TYPE="radio" NAME="rad" VALUE="radio_button2" onClick=0> <INPUT TYPE="radio" NAME="rad" VALUE="radio_button3" onClick=0> <INPUT TYPE="radio" NAME="rad" VALUE="radio_button4" onClick=0>The onClick event handler in this markup acts as a work-around for a bug in Netscape 2.0. Without the onClick event handler JavaScript will return the buttons in reverse order: 3, 2, 1, 0 -- instead of the proper 0, 1, 2, 3. The onClick handler does nothing, as its value is set to zero.
Following is an example of testing which button is selected. The for loop in the testButton function cycles through all of the buttons in the "rad" group. When it finds the button that's selected, it breaks out of the loop and displays the button number (remember: starting from 0).
form_radio.html <CD> <HTML> <HEAD> <TITLE>Radio Button Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testButton (form){ for (Count = 0; Count < 3; Count++) { if (form.rad[Count].checked) break; } alert ("Button " + Count + " is selected"); } </SCRIPT> </BODY> <FORM NAME="testform"> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testButton(this.form)"><BR> <INPUT TYPE="radio" NAME="rad" Value="rad_button1" onClick=0><BR> <INPUT TYPE="radio" NAME="rad" Value="rad_button2" onClick=0><BR> <INPUT TYPE="radio" NAME="rad" Value="rad_button3" onClick=0><BR> </FORM> </HTML>If you want to have more than one set of radio buttons in your form, just give them different names. For example, the first group of buttons might be named "rad1," and the second "rad2." The browser will allow you to select a button from each group.
Setting a radio button selection is even easier. If you want the form to initially appear with a given radio button selected just added the CHECKED attribute to the HTML markup for that button:
<INPUT TYPE="radio" NAME="rad" Value="rad_button1" CHECKED onClick=0><BR>
You can also set the button selection programmatically with JavaScript, using the checked property (there is also a selected property, but it is not properly functioning in all platforms supported by Netscape 2.0). Just specify the index of the radio button array you want to select.
form.rad[0].checked = true; // sets to first button in the rad group
Using Check Boxes
Check boxes are stand-alone elements; that is, they don't interact with neighboring elements like radio buttons do. Therefore they are a bit easier to use. Using JavaScript you can test if a check box is checked or not using the checked property. Likewise, you can set the checked property to add or remove the checkmark from a check box.
form_check.html <CD> <HTML> <HEAD> <TITLE>Checkbox Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testButton (form){ alert (form.check1.checked); } </SCRIPT> </BODY> <FORM NAME="testform"> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testButton(this.form)"><BR> <INPUT TYPE="checkbox" NAME="check1" Value="Check1">Checkbox 1<BR> <INPUT TYPE="checkbox" NAME="check2" Value="Check2">Checkbox 2<BR> <INPUT TYPE="checkbox" NAME="check3" Value="Check3">Checkbox 3<BR> </FORM> </HTML>
As with the radio button object, add a CHECKED attribute to the HTML markup for that check box if you wish to set a check box when the form first appears.
<INPUT TYPE="checkbox" NAME="check1" Value="0" CHECKED>Checkbox 1<BR>
You can also set the button selection programmatically with JavaScript, using the checked property. Just specify the name of the checkbox you want to check. Remember that you can check multiple check boxes.
form.check1.checked = true;
Using Text Areas
Text areas are used for multiple-line text entry. The default size of the text box is 1 row by 20 characters. You can change the size using the COLS and ROWS attributes. Here's a typical example of a text area with a text box 40 characters wide by 7 rows:
<TEXTAREA NAME="myarea" COLS="40" ROWS="7"> </TEXTAREA>
You can use JavaScript to read the contents of the text area box. This is done with the value property. Example:
form_textarea.html <CD> <HTML> <HEAD> <TITLE>Text Area Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function seeTextArea (form) { alert (form.myarea.value); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform"> <INPUT TYPE="button" NAME="button3" Value="Test" onClick="seeTextArea(this.form)"> <TEXTAREA NAME="myarea" COLS="40" ROWS="5"> </TEXTAREA> </FORM> </BODY> </HTML>
You can preload text into the text area in either of two ways. You can enclose the text between the <TEXTAREA> and </TEXTAREA> tags, as shown in Figure 16-2. This method is useful if you wish to include hard returns, as these are retained in the text area box. Or, you can set it programmatically with JavaScript (but in this case you cannot add hard returns). Here's an example of the first method:
<TEXTAREA NAME="myarea" COLS="40" ROWS="7"> Initial text displayed here </TEXTAREA>
Using JavaScript you set the text area value:
formname.textarea.value = "Text goes here";
- formname is the name of the form.
- textarea is the name of the textarea.
- "Text goes here" is the text you want to display
<Figure 16-2. Default text can be placed between <TEXTAREA> tags.>
Text you write to the text area is treated as "unformatted." Any markup tags you use --
such as <P> or <BR> for line breaks, appears as-is in the text area box.
Using Selection Lists
List boxes let you pick the item you want out of a multiple-choice box. The listbox itself is created with the <SELECT> tag, and the items inside it are created by one or more <OPTION>. You can have any number of <OPTION> tags in a list. The list is terminated with a </SELECT> tag.
The list can appear with many items showing at once, or it can appear in a drop-down box -- normally you see one item at a time, but click to see more. The markup for the two styles is identical, except for the optional SIZE attribute. Leave off SIZE to make a drop-down box; use SIZE to make a list box of the size you wish.
Example of drop down list (displays only one item unless you click on the list):
<SELECT NAME="list"> <OPTION>This is item 1 <OPTION>This is item 2 <OPTION>This is item 3 <OPTION>This is item 4 </SELECT>
Example of drop down list (displays all four items):
<SELECT NAME="list" SIZE="4"> <OPTION>This is item 1 <OPTION>This is item 2 <OPTION>This is item 3 <OPTION>This is item 4 </SELECT>
Use the selectedIndex property to test which option item is selected in the list. The item is returned as an index value, with 0 being the first option, 1 being the second, and so forth (if no item is selected the value is -1). Here's a working example:
form_select.html
<CD> <HTML> <HEAD> <TITLE>List Box Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testSelect(form) { alert (form.list.selectedIndex); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform" ACTION="" METHOD="GET"> <INPUT TYPE="button" NAME="button" Value="Test" onClick="testSelect(this.form)"> <SELECT NAME="list" SIZE="3"> <OPTION>This is item 1 <OPTION>This is item 2 <OPTION>This is item 3 </SELECT> </FORM> </BODY> </HTML>
If you want the text of the selected list item instead of the index, use this in the testSelect function:
function testSelect (form) { Item = form.list.selectedIndex; Result = form.list.options[Item].text; alert (Result); }
Other Things You Can Do With <SELECT> Objects
The <SELECT> object is the er, object of a lot of confusion to many JavaScript programmers. So here's a rundown of what you can do with the list boxes created with the <SELECT> object. In all of the below, formname is the unique name of the form, and selectname is the unique name of the select object you want to test.
- Determine the index of the selected option with:
index is the of the option that is selected (numbering starts at 0)
- Set the selected option with:
index is the index value of the option you want selected (numbering starts at 0)
- Determine the text of the selected item with:
Result = formname.selectname.options[Item].text;
- Determine how many items are in the <SELECT> object with:
- Set the text of a select option, as long as you also tell JavaScript to reload the page:
history.go(0);
index is the index of the option that you want to change
"Text" is the text you want to change to
Testing for Multiple Selections With the selected Property
You can allow for multiple selections in a list by using the MULTIPLE attribute in the <SELECT> tag. The JavaScript to process this is a bit more involved, because you need to test each item of the list to see if it's selected. A perfect way to do this is to use a for counter that enumerates through all the <OPTION> tags in a <SELECT> object (you control the number of iterations of the for loop by using the length property of the select object).
For example, say you have a list with five items on it, and the user selects the first and fourth item. The following JavaScript program will display:
Option 0 is selected
Option 3 is selected
in the alert box. Once again note that the option items are numbered starting from zero. The first option is 0, the second is 1, and so forth.
form_multiple.html <CD> <HTML> <HEAD> <TITLE>Multiple Selection Test </TITLE> <SCRIPT LANGUAGE="JavaScript"> function selectedItem (form) { var Temp = ""; for (Count = 0; Count < form.list.length; Count++) { if (form.list[Count].selected) Temp += "Option " + Count + " is selected\n"; } alert (Temp); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform"> <INPUT TYPE="button" NAME="button3" Value="Test" onClick="selectedItem(this.form)"> <SELECT NAME="list" SIZE="5" MULTIPLE> <OPTION>This is item 1 <OPTION>This is item 2 <OPTION>This is item 3 <OPTION>This is item 4 <OPTION>This is item 5 </SELECT> </FORM> </BODY> </HTML>
Other Events You can Trigger Within a Form
I've used the onClick event handler in all of the examples in this chapter because that's the one you are most likely to deal with in your forms. Yet JavaScript supports a number of other event handlers as well. Use these as the need arises, and the mood fits. The event handlers used with form object are:
- onFocus -- an event is triggered with a form object gets input focus (the insertion point is clicked there).
- onBlur -- an event is triggered with a form object loses input focus (the insertion point is clicked out of there).
- onChange -- an event is triggered when a new item is selected in a list box. This event is also trigged with a text or text area box loses focus and the contents of the box has changed.
- onSelect -- an event is triggered when text in a text or text area box is selected.
- onSubmit -- an event is triggered when the form is submitted to the server (more about this important hander later in the chapter).
Submitting the Form to the Server
In all of the examples above I've limited the action of the form to within JavaScript only. Many forms are designed to send data back to the server. This is called "submitting" the form, and is accomplished using either of two JavaScript instructions: the onSubmit event handler or the submit method. In most instances, you use one or the other, not both!
- Place the onSubmit event hander in the <FORM> tag. This tells JavaScript what it should do when the user clicks the Submit button (this is a button defined as TYPE="submit").
- Place the submit instruction anywhere in your JavaScript. It can be activated by any action, such as clicking a form button that has been defined with the onClick event handler.
Using onSubmit
Here's an example of using the onSubmit event handler to send mail. The onSubmit event handler tells JavaScript what to do when the user clicks the Submit button: it should call the mailMe() function, where the fields are appended to a mailto: URL. Netscape automatically opens a new mail window with the fields filled in. Write the body of the message, and send the mail off to the recipient.
onsubmit.html <CD> <HTML> <HEAD> <TITLE>onSubmit Test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function mailMe(form){ Subject=document.testform.inputbox1.value; CC= document.testform.inputbox2.value; BCC= document.testform.inputbox3.value; location = "mailto:[email protected]?subject="+Subject+ "&Bcc="+BCC+"&cc="+CC; return true; } </SCRIPT> </HEAD> <BODY> <FORM NAME="testform" onSubmit="return mailMe(this.form)"> Subject of message: <BR> <INPUT TYPE="text" NAME="inputbox1" VALUE="This is such a great form!" SIZE=50><P> Send cc to: <BR> <INPUT TYPE="text" NAME="inputbox2" VALUE="" SIZE=50><P> Send blind cc to: <BR> <INPUT TYPE="text" NAME="inputbox3" VALUE="" SIZE=50><P> <INPUT TYPE="submit"><BR> </FORM> </BODY> </HTML>
Using submit
In the next example the submit method is used instead. The script is little changed, except that the onSubmit handler is removed, and an onClick hander for a renamed form button is added in its place. The submit() method replaces the return true statement in the previous example. (Personally, I prefer the submit method because it provides a little more flexibility. But either one will work.)
submit.html <CD> <HTML> <HEAD> <TITLE>test</TITLE> <SCRIPT LANGUAGE="JavaScript"> function mailMe(form){ Subject=document.testform.inputbox1.value CC= document.testform.inputbox2.value BCC= document.testform.inputbox3.value location = "mailto:[email protected]?subject="+Subject+ "&Bcc="+BCC+"&cc="+CC document.testform.submit(); } </SCRIPT> </HEAD> <BODY> <FORM NAME="testform"> Subject of message: <BR> <INPUT TYPE="text" NAME="inputbox1" VALUE="This is such a great form!" SIZE=50><P> Send cc to: <BR> <INPUT TYPE="text" NAME="inputbox2" VALUE="" SIZE=50><P> Send blind cc to: <BR> <INPUT TYPE="text" NAME="inputbox3" VALUE="" SIZE=50><P> <INPUT TYPE="button" VALUE="Send Mail" onClick="mailMe()"><BR> </FORM> </BODY> </HTML>
I'll reserve the remaining full details of using the onSubmit and submit instructions for Chapter 18, "Using CGI with JavaScript." At first blush it looks like you can use the mailto: URL as the ACTION string for the form. This should have the effect of automatically sending the contents of the text boxes straight to the recipient's mail box. The syntax looks like this:
<FORM NAME="testform" ACTION="mailto:[email protected]">In fact, this method does work with the initial release of Netscape 2.0. But since it is possible to submit a form without the user knowing (using the submit method), Netscape has removed this functionality in subsequent releases. This is a minor security issue where e-mail addresses can be picked up and mailed back to someone. These e-mail addresses could then be used for advertising or marketing purposes.
Validating Form Data Using JavaScript
The World Wide Web "grew up" when they added the ability to display forms. In the days before forms, the Web was only mildly interactive, with just hypertext links to take readers from location to location. Forms allow users to truly interact with the Web. For example, readers can specify search queries using a simple one-line text box.
As you've read earlier in the chapter, forms on the Web consist of two parts: the form itself, which is rendered in the browser, and a CGI script or program located on the server. This script processes the user's input. While it's not exactly rocket science, a stumbling block in creating great Web forms is writing the CGI program. In most cases these programs are written in Perl or C, and can be a bother to implement and debug. A primary job of the CGI program is to validate that the reader has provided correct data, and this can requires pages of code.
JavaScript changes that. With JavaScript you can check the data provided by the reader before
it's ever sent to the CGI program. In this way the CGI program can be kept to a bare minimum.
And, because the data is only sent after it has been validated, the server need not be bothered until
the form entry is known to be good. This saves valuable server resources.
Input Validation Routines
Most form validation chores revolve around basic data checking: does the user remember to fill in an box? Is it have the right length? Does it contain valid characters? With most forms you can readily answer these questions with a small handful of validation routines. You can write them yourself, or use the over two dozen validation routines included with this book.
A typical validation routine is determining if an input box contains only numeric digits. If the entry contains non-numeric characters, you can ask the user to enter the correct data. A ready-made routine for this is the isNumberString function, which returns the value 1 if the string contains only numbers, and 0 if it contains any non-numeric characters. To use it, provide the data string as the parameter. The value returned by the function tells you if the data is valid. Here's an example:
valid_simple.html <CD> <HTML> <HEAD> <TITLE>Test Input Validation</TITLE> <SCRIPT LANGUAGE="JavaScript"> function testResults (form) { TestVar = isNumberString (form.inputbox.value) if (TestVar == 1) alert ("Congratulations! You entered only numbers"); else alert ("Boo! You entered a string with non-numbers characters"); } function isNumberString (InString) { if(InString.length==0) return (false); var RefString="1234567890"; for (Count=0; Count < InString.length; Count++) { TempChar= InString.substring (Count, Count+1); if (RefString.indexOf (TempChar, 0)==-1) return (false); } return (true); } </SCRIPT> </HEAD> <BODY> <FORM NAME="myform"> Enter a string with numbers only: <INPUT TYPE="text" NAME="inputbox" VALUE=""> <INPUT TYPE="button" NAME="button" Value="Click" onClick="testResults(this.form)"> </FORM> </BODY> </HTML>
Note that the isNumberString function is also smart enough to check for an empty input box. It
treats an empty box as an invalid entry, returning a 0. If this test were not provided a blank entry
would be treated as valid input.
Overview of Validation Routines
Here is a run down of some of the other input validation routines provided on the CD-ROM
included with this book. These -- and other -- routines are more completely documented in
Chapter 13, "Plug-and-Play Routines." Also included here are various string processing routines
that are often helpful when working with forms.
Data Validation Routines
Routine | What it does |
allowInString | Allow specified characters in string |
allowNotInString | Don't allow specified characters in string |
isAlphabeticChar | Checks if string (one character) is an alphabetic |
isAlphabeticString | Checks if string (multiple characters) is an alphabetic |
isNumberChar | Checks if string (one character) is a number |
isNumberString | Checks if string (multiple characters) is a number |
isCharUpper | Check is string (multiple characters) is uppercase |
isCharLower | Check is string (multiple characters) is lowercase |
isPunc | Check is string (one character) is punctuation |
isUSZip | Check if string is a valid 5 or 9 digit US Zip code |
isWithinRange | Check if number value is within a specified range |
isBlank | Check if entry is blank |
isNotBlank | Check of entry is not blank |
Mask | Validate entry against pre-defined input mask |
Input Processing Routines
Routine | What it does |
formatDollar | Convert number value into dollar format |
leftTrim | Trim extra spaces on left of string |
rightTrim | Trim extra spaces on right of string |
leftString | Return only X characters from left of string |
rightString | Return only X characters from right of string |
stripSpaces | Strip all spaces from string |
stripChar | Strip all occurrences of X character in string |
stripCharString | Strip all occurrences of specified characters in string |
padTextSuffix | Pad end of string to length with X character |
padTextPrefix | Pad beginning of string to length with X character |
initUpper | Capitalize first letter in each word |
initUpperQualify | Capitalize first letter in each word following lexical rules |
parser | Parse string into component parts |
testStringLength | Determines if string matches length requirements |
Practical Examples of Input Validation
Here's an two example of how to use JavaScript for form input validation. Four text boxes are provided; beside each is a button. Enter text into one of the boxes, and click the button beside it. If you have not entered valid data, you are asked to re-enter it. Figure 16-3 shows the valid.htm document displayed in Netscape.
- Box 1 tests for a valid e-mail address. In the example the test is limited to merely looking for a @ symbol.
- Box 2 tests for input of exactly five characters.
- Box 3 tests for input of three or more characters.
- Box 4 tests for non-blank input.
valid.htm <CD> <HTML> <HEAD> <TITLE> Verifying Form Input with JavaScript</TITLE> <SCRIPT LANGUAGE="JavaScript"> function runTest(form, button) { Ret = false; if (button.name == "1") Ret = testBox1(form); if (button.name == "2") Ret = testBox2(form); if (button.name == "3") Ret = testBox3(form); if (button.name == "4") Ret = testBox4(form); if (Ret) alert ("Successful input!"); } function testBox1(form) { Ctrl = form.inputbox1; if (Ctrl.value == "" || Ctrl.value.indexOf ('@', 0) == -1) { validatePrompt (Ctrl, "Enter a valid email address") return (false); } else return (true); } function testBox2(form) { Ctrl = form.inputbox2; if (Ctrl.value.length != 5) { validatePrompt (Ctrl, "Provide five characters") return (false); } else return (true); } function testBox3(form) { Ctrl = form.inputbox3; if (Ctrl.value.length < 3) { validatePrompt (Ctrl, "Provide at least three characters") return (false); } else return (true); } function testBox4(form) { Ctrl = form.inputbox4; if (Ctrl.value == "") { validatePrompt (Ctrl, "Provide a value for this box") return (false); } else return (true); } function runSubmit (form, button) { if (!testBox1(form)) return; if (!testBox2(form)) return; if (!testBox3(form)) return; if (!testBox4(form)) return; alert ("All entries verified OK!"); //document.test.submit(); // un-comment to actually submit form return; } function validatePrompt (Ctrl, PromptStr) { alert (PromptStr) Ctrl.focus(); return; } </SCRIPT> </HEAD> <BODY> <FORM NAME="test" ACTION="https://domain.com/cgi-bin/val.cgi" METHOD=GET> Enter an e-mail address (e.g. [email protected]): <BR> <INPUT TYPE="text" NAME="inputbox1"> <INPUT TYPE="button" NAME="1" VALUE="Test Input" onClick="runTest(this.form, this)"><P> Enter five characters only: <BR> <INPUT TYPE="text" NAME="inputbox2"> <INPUT TYPE="button" NAME="2" VALUE="Test Input" onClick="runTest(this.form, this)"><P> Enter three or more characters: <BR> <INPUT TYPE="text" NAME="inputbox3"> <INPUT TYPE="button" NAME="3" VALUE="Test Input" onClick="runTest(this.form, this)"><P> Enter anything (don't leave blank): <BR> <INPUT TYPE="text" NAME="inputbox4"> <INPUT TYPE="button" NAME="4" VALUE="Test Input" onClick="runTest(this.form, this)"><P><P> <INPUT TYPE="button" NAME="Submit" VALUE="Submit" onClick="runSubmit(this.form, this)"><P> </FORM> </BODY> </HTML>
<Figure 16-3. The valid.htm document, ready for text input.>
Experiment with the valid.htm to see how the various validation routines work. The example actually double-checks each input; then checks again when you click the Submit button. In actual use, you need only test once, typically when the Submit button is pressed. When all the blanks have been entered correctly the script announces " All entries verified OK!" The focus method is used in the above example to set focus in a text box to prompt the user that the input for that box is incorrect. Under some platforms (such as Windows) the focus() method doesn't always display a flashing bar when the insertion point is placed in a text box. Focus is properly set in the desired box, but there may not be visual confirmation of it. Therefore, don't assume the user is aware that focus has been returned to the box. If your form contains many input boxes, specify the box that needs correct input by name.
Validating Non-text Controls
The text control is the natural candidate for form validation (hidden text controls need no user validation, and in Netscape 2.0 the value of the password text control cannot be read). In the previous examples you've seen how to validate the content of text controls. Here's how to validate other commonly use controls and control structures in HTML forms.
In all of the following, the form name is myform, and the control name is control. A typical example:
<SCRIPT LANGUAGE="JavaScript"> function testform() { alert (document.myform.control.value) } </SCRIPT> <FORM NAME="myform"> <TEXTAREA NAME="control" COLS=40 ROWS=5> </TEXTAREA> <INPUT TYPE="button" VALUE="Click" onClick="testform()"> </FORM>
Validating Textareas
As with text boxes, use the value property to test the content of textareas. Examples:
Ret = document.myform.control.value; // assigns content to Ret Ret = document.myform.control.value.length; // assigns length of content to Ret Ret = document.myform.control.value.indexOf ("\n") // value 0 or above indicates hard return
Validating Check boxes
The check box controls are either on or off. Use the checked property of the control to validate if a checkbox is checked or not checked. Examples:
Ret = document.myform.control.checked; // true if checked; false if not checked
Validating Radio Buttons
Only one radio button in a group can be selected at one time. You can check which one is selected using a loop like the following (this is described earlier in the chapter; it checks three buttons in the rad group):
for (Count = 0; Count < 3; Count++) { if (form.rad[Count].checked) break; }
You can use this loop to determine if none of the radio buttons are selected. This may be needed if you must initially display all of the radio buttons in a group as unselected, but require one of them to be selected.
Selected = false; for (Count = 0; Count < 3; Count++) { if (form.rad[Count].checked) { Selected = true; break; } } if (Selected) // a radio button is selected else // no radio button is selected
Validating Selection Lists
You may validate that at least one option in a selection list is selected with the following for loop:
Selected = false; for (Count = 0; Count < document.myform.control.length; Count++) { if (form.list[Count].selected) Selected = true; } if (Selected) // an option is selected else // no option is selected
When using multiple-choice selection lists you can verify that at least a certain number of options are selected with the following (this assumes at least three options in the list must be selected to pass verification):
Selected = 0; for (Count = 0; Count < document.myform.control.length; Count++) { if (form.list[Count].selected) Selected++; } if (Selected < 3) // fewer than 3 selected else // 3 or more selected
You can use opposite logic to verify that no more than a certain number of options are selected:
Selected = 0; for (Count = 0; Count < document.myform.control.length; Count++) { if (form.list[Count].selected) Selected++; } if (Selected > 3) // more than three selected else // 3 or less selected
Comments are welcome
Copyright © 1996 Gordon McComb and
Revised: October 31, 1996
URL: https://webreference.com/content/jssource/chap16.html