Chapter 70. Validating Form Input


Even though you need server-side coding to process form data, you can use good old client-side scripting to review the visitor's submission before it goes to the Web server. This process is called validation, and it's a very good idea for most types of forms.

A validation pass helps to prevent errors, both intentional and accidental, from confusing or crashing the server-side code that eventually receives the form data. Say your form asks visitors to supply an email address so that the server-side form handler can send out a confirmation email. Obviously, you need the visitor to supply an email address, or the server-side code won't work right. If someone out there gets clever and tries to leave the field blank or types in something other than an email address, the validation script catches it and asks for a correction. Of course, the visitor could still supply an invalid email address, but at least the validation script screens out a good chunk of potentially bad data.

GEEKSPEAK

Validating form input means reviewing it for accuracy before sending it off to the Web server.


Any validation script requires close coordination with the structure of the form. And since no two forms are alike, there's no such thing as an all-purpose, one-size-fits-all validation script. For this reason, the Toolkits in this topic aren't like the others in this book, in that you don't just copy the code to your Web site. You start with the Validation Script Skeleton instead, and then you pick from the rest of the Toolkits, adding the validation features that you need for your particular form.

TOOL KIT

Validation Script Skeleton

This Toolkit contains the skeleton for a form validation script. By itself, it doesn't validate anythingyou need to add other blocks of code for that. The other Toolkits in this topic give you the actual validation routines. Pick and choose the ones you need, and add them to this framework.

[View full width]

<script language="JavaScript"> /* If you're adding this script to an external JavaScript file, you don't need the script tags at the beginning and end of this listing. If you're embedding the script on a Web page, make sure it's the same page that contains the form. */ function validateForm() { /* Add components from the other Toolkits here. */ return true; /* Assuming the form data passes all validation checks, the above command gives the go-ahead for the browser to submit the form to the Web server. */ } </script>

You need one more thing besides this framework for the validation function: a form that runs the script upon submission. Add the onSubmit event to the form tag, like so:

[View full width]

<form name="formname" action="formaction" method="formmethod" onSubmit="return validateForm();">

Of course, you should insert the appropriate values in the name, action, and method attributes for your particular form.


TOOL KIT

Checking for an Email Address

Add this block of code to the validation script to check that the visitor has entered an email address in a text field.

[View full width]

var email = new String(document.formname.textfieldname.value); /* In the line of code above, insert the name of the form and the name of the text field that contains the email address. This statement creates a variable called email to hold whatever the visitor typed in the field. */ if (email.indexOf("@") == -1) { /* The statement above checks to see if the field contains an at-sign (@). If it doesn't, the validation script assumes that whatever the visitor typed isn't an email address. */ alert("You must supply a valid email address."); /* The statement above displays an error message in a popup window. */ document.formname.textfieldname.select(); /* The statement above selects the email field of the form. */ return false; /* The statement above cancels the form submission. */ }


TOOL KIT

Checking Required Text Fields

Add this block of code to the validation script to check that the visitor has filled out all required text fields. This Toolkit also works with password fields and text areas.

[View full width]

var field01 = new String(document.formname.requiredfield01.value); var field02 = new String(document.formname.requiredfield02.value); var field03 = new String(document.formname.requiredfield03.value); var field04 = new String(document.formname.requiredfield04.value); var field05 = new String(document.formname.requiredfield05.value); /* The above statements create variables for each of the required text fields in your form. If you have fewer than five, omit the lines you don't need. If you have six or more, just add lines to the script, using these as a template. */ var pass = true; /* The line above creates a Boolean (true/false) variable called pass and sets it to true. */ /* The if/then blocks below check to see if the visitor has filled out each required text field. If the script comes across a missed field, pass equals false. You need one if/then block per required text field, so adjust these according to your particular form, removing unneeded blocks or adding extra ones. */ if (field01.length == 0) { pass = false; } if (field02.length == 0) { pass = false; } if (field03.length == 0) { pass = false; } if (field04.length == 0) { pass = false; } if (field05.length == 0) { pass = false; } /* The following block of code tests the value of the pass variable. If pass equals false, which is to say if at least one of the required text fields is blank, then the browser displays an error message and stops the submission of the form. */ if (pass == false) { alert("You must fill out all required fields."); return false; }


TOOL KIT

Checking Required Lists and Menus

Add this block of code to the validation script to check that the visitor has filled out all required lists and menus.

The code assumes that your list or menu begins with a preselected default option like this:

 <option selected>Choose an option...</option> 

You can change the Choose an option... text between the option tags to match your specific form. Just make sure you also change the text as it appears in the following code:

[View full width]

var list01 = document.formname.requiredlist01; var list01Text = list01.options[list01.selectedIndex].text; var list02 = document.formname.requiredlist02; var list02Text = list02.options[list02.selectedIndex].text; var list03 = document.formname.requiredlist03; var list03Text = list03.options[list03.selectedIndex].text; var list04 = document.formname.requiredlist04; var list04Text = list04.options[list04.selectedIndex].text; var list05 = document.formname.requiredlist05; var list05Text = list05.options[list05.selectedIndex].text; /* The code above creates new variables for the required lists and menus in your form and gets the text of the selected option in each. If you have fewer than five lists or menus, delete the lines that you don't need. If you have six or more, add new lines. The line below creates a new variable called pass and sets its value to true. */ var pass = true; /* The if/then blocks that follow make sure that none of your required lists or menus still show the default option. If at least one list or menu does, the value of pass becomes false. You need one if/then block per required list or menu, so delete the blocks you don't need, or add similar blocks if you need more than five. */ if (list01Text == "Choose an option...") { pass = false; } if (list02Text == "Choose an option...") { pass = false; } if (list03Text == "Choose an option...") { pass = false; } if (list04Text == "Choose an option...") { pass = false; } if (list05Text == "Choose an option...") { pass = false; } /* The if/then block below checks the value of pass. If false, the form doesn't submit. */ if (pass == false) { alert("You must fill out all required fields."); return false; }


TOOL KIT

Checking for Alphanumeric Characters Only

Add this block of code to the validation script to check that the visitor has entered only alphanumeric characters in a text field, text area, or password field.

[View full width]

var field = new String(document.formname.fieldname.value); /* The code above creates a new variable for the value of the field in question. Replace formname with the name of the form and fieldname with the name of the field that you want to check. The line below creates the variable called pass and sets its value to true. */ var pass = true; /* The next block of text creates a for/next loop. The script looks at each character in the field and decides if this character is a letter or number. If not, the value of pass becomes false. */ for (var x = 0; x < field.length; x++) { if (field.charCodeAt(x) < 48 || (field.charCodeAt(x) > 57 && field.charCodeAt(x) < 65) || (field.charCodeAt(x) > 90 && field.charCodeAt(x) < 97) || field.charCodeAt(x) > 122) { pass = false; } } /* Now, if pass equals false, the browser displays an error message, deletes the value of the offending field, and automatically selects this field so that the visitor can try again. */ if (pass == false) { alert("Your entry contains characters other than letters and numbers."); document.formname.fieldname.value = ""; document.formname.fieldname.select(); return false; }


TOOL KIT

Checking for Matching Password Fields

Add this block of code to the validation script to check that the visitor has matching password fields. You know the routine: One field asks for a password, and the next field asks the visitor to retype the password. This script also works with text fields and text areas.

[View full width]

var password = new String(document.formname.passwordname.value); var retype = new String(document.formname.retypename.value); /* The code above creates new variables for the values of the password field and the retype field. Replace formname with the name of the form, replace password name with the name of the password field, and replace retypename with the name of the field where the visitor retypes the password. */ if (password.valueOf() != retype.valueOf()) { alert("Your password fields don't match."); document.formname.retypename.value = ""; document.formname.passwordname.select(); return false; } /* The if/then block above compares the value of password with the value of retype. If they don't match, the browser displays an error message, clears the value of the retype field, selects the password field, and stops submission. */


TOOL KIT

Verifying an "I Agree" Checkbox

Add this block of code to the validation script to verify that the visitor has checked an "I Agree" checkbox, like when the visitor has to agree to the terms of service or your privacy policy or what have you.

[View full width]

if (document.formname.checkboxname.checked == false) { alert("You must agree to proceed."); return false; } /* The if/then block above looks to see if the checkbox is checked. If not, the browser displays an alert message and stops submission. Replace formname with the name of the form, and replace checkboxname with the name of the "I Agree" checkbox. */




Web Design Garage
Web Design Garage
ISBN: 0131481991
EAN: 2147483647
Year: 2006
Pages: 202
Authors: Marc Campbell

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net