|
JavaScript Tip:
Basic Form Validation With JavaScript
by Larisa Thomason,
Senior Web Analyst,
Keynote NetMechanic
Although forms are a great way to add interactivity to your site and receive immediate feedback from visitors, there's one problem: you're dependent on your visitors to send you information that makes sense! Programmers call that the "garbage in, garbage out principle." One way to screen out the garbage form data is to validate visitor inputs before the form gets submitted.
Start With A Simple Form
Like most programming tasks, form validation can be as simple or as complex as you want to make it. We're going to create a simple function that just checks to see if a field has information in it and use it to make sure that required fields are filled out.
Note that we are not checking to see if the information in the field is valid (as in a real email address or numbers in a numeric field). This will be the subject of a later article.
In this example, we'll use a simple form that collects a visitor's name, email address, and phone number and use a form validation function to check to see that information gets entered into all three fields.
Check For Required Fields
Although it does add complexity to the function, we're going to have JavaScript validate each element separately and alert the user to each individual error. That makes it much easier for the user to enter the correct information and successfully submit the form!
First, create a simple form and use the NAME attribute to name it "contact." Although a form name technically isn't required, it's still a good idea to name your forms and form elements. Form names and element names are recommended if you plan to process the form using a CGI script.
Next, insert this JavaScript function into the document's HEAD section:
<script language="javascript"
type="text/javascript">
<!-- hide script from older browsers
function validateForm(contact)
{
if(""==document.forms.contact.fullName.value)
{
alert("Please enter your full name.");
return false;
}
if(""==document.forms.contact.email.value)
{
alert("Please enter your email address.");
return false;
}
if(""==document.forms.contact.phoneNum.value)
{
alert("Please enter your phone number.");
return false;
}
}
stop hiding script -->
</script>
|
This function has three IF statements that are almost identical. The first IF statement checks to see if the textbox called "fullName" is blank. If so, it returns a JavaScript Alert (a pop-up box) that reminds the visitor to enter his or her name. The other two IF statements function the same way.
Note the syntax we use to refer to the form and text box:
document.forms.contact.fullName.value
|
This specifically identifies the form named "contact" and the text box named "fullName." It's important to be this specific to avoid confusion - especially when there's more than one form on the Web page.
Then, include an onSubmit statement that calls the function when the form is submitted. Include it inside the opening FORM tag:
<form name="contact" method="post" action=""
onSubmit="return validateForm(contact);">
|
Add A Little Focus
This form validation function works just fine. Still, we can make it more user-friendly and accessible by sending the cursor directly to the field containing the error.
Just add one line of JavaScript after each IF statement like this - making sure to change the field name each time. The added line is in bold:
if(""==document.forms.contact.phoneNum.value)
{
alert("Please enter your phone number.");
document.forms.contact.phoneNum.focus();
return false;
}
|
This addition means that the cursor goes automatically to the field that generated the error message.
That way, the visitor knows immediately which field has a problem and can correct it quickly. It may not seem that useful on a short form like this example, but it's tremendously valuable for longer forms. Anything that makes a form easier to complete will help ensure that visitors actually stick around and complete the information!
Other ways to customize your forms include:
This example file shows the entire form in action with all the alert messages and validation functions. Experiment with it by leaving out certain fields and noticing how the JavaScript function reacts.
Hit the Submit button as much as you like! It isn't a functioning form, so you won't be sending us any "garbage" to deal with.
Consider External JS Files
Remember that form validation can be pretty complex and the amount of JavaScript code needed for a complex form can be huge. You may want to consider placing your form validation function inside an external JavaScript file and calling the external file inside the HEAD section instead of packing it with a lot of code.
Our February 2002 article contains instructions on how to create both external JavaScript and CSS files.
Once you've created the external file, replace the JavaScript code in your HEAD section with this one line instruction to use the external file.
<script src="external.js" language="javascript"
type="text/javascript">
|
The form validation we've done here is really basic, but JavaScript is capable of much more complicated validation. If subscribers are interested, we'll consider doing a more advanced story that covers more complex techniques later this year. You're invited to
send suggestions and code that has worked - or not! - for you.
|