Description
This article discusses how to use JavaScript to validate important types of form data, including names, addresses, URLs, email addresses, phone numbers, zip codes, expiration dates and credit card numbers (Visa, Master Card, Discover, and American Express, in both Canadian and US formats, with either 13, 14, 15 or 16 digit account numbers). Each data validation function returns an array of valid inputs that were detected, and has the ability to filter and reformat data to desired appearances and standards. If no valid input is detected, then an error code is returned. In addition to providing definitions for each error code number, the JavaScript form validation script also provides associated human-readable error messages which explain the error after it has occurred.
Also, a user input validation function is provided which stops falsified user information from being submitted to business Web sites. This function is easy to add to any Web form by creating a list of form objects, and registering the function as the onsubmit
event handler for the form. The programming logic allows for relations to be expressed between associated form fields when performing user input validation. For added flexibility, the validation process allows the form creator to permit specific data entry fields to contain unverified or unusual data at the time the form is successfully validated and submitted.
Introduction
This validation script offers a collection of validation functions, and an easy way to use them in your form with JavaScript. Ideally, validation should be helpful to users and make it easier for customers to fill out forms. Be aware that there are some precautions to take note of, which are discussed later on.
The script is written to make validation easy to use. While primarily intended for text fields, it's also applicable to other fields which have pre-programmed values. When working with text fields it's able to validate the field value itself, but when working with other fields it's able to validate the entire field in combination with other fields and functions.
The JavaScript validation programming interface consists of four components:
- Low-level processing functions for numerical values, text, and whitespace.
- Validation functions for each type of data
- Validation handler used for
onsubmit
, which supports generic form validation using a list of form elements, or fine-tuned validation by using a validation profile customized for your form - Definitions of error codes and user-friendly error code messages
We display an example form along with its source code to
show how the validation program is used. Then we explain how to
use the built-in validation functions, how to add a customized validation function,
how to add your own error codes and error messages, and finally, how to register
the validation function as the onsubmit
event handler for your
form.
Data Validation Precautions
A serious concern with data validation is that a validation script sometimes is unable to recognize acceptable values, or that it may be non-functional depending on browser settings or other issues. If an error occurred when loading a script in a page, a customer might not be able to submit the order. In addition, it tends to make security managers forget that malicious users can intentionally disable scripts. Nothing from a form should ever be blindly trusted if a critical area of security might be compromised if an unexpected value was submitted.
For businesses there's another problem that is just as important as security. Customers shouldn't be prevented from placing orders due to a validation script which didn't consider all cases of valid input, or which commits some other logical error.
An example is Frys.com, where improper form validation prevents many people from submitting orders. Validation code tries to prevent duplicate order submissions in the final step of ordering. Here, a JavaScript logic error results in the form's being disabled before any order is submitted in many cases; on Opera, this problem is repeatable every time, so it's actually impossible to order from Frys.com with the Opera browser due to this bug.
So far as I know, this problem hasn't been corrected, and it's been present for more than a year. From a business standpoint, this is just as serious as security errors. Web sites should be lenient about permitting users to submit information which may in fact be correct, even when the JavaScript validation code thinks it's wrong. Business ordering systems should allow the user to submit the form after confirming their data for the third time. The JavaScript error code can be submitted in a hidden field.
Even though these validation functions have been refined over seven years and they can be considered to be production grade, one should still take extra precautions to make sure that people can submit their data. There will still be cases when the validation script might be wrong or when there should still be a way around it.
An example form
This example shows a typical form used to gather data on a Web site. The source code is given below.
JavaScript code
HTML code
This is a somewhat complicated example to show you the power of form validation. Next, we show you how form validation is performed, one step at a time.
Available validation functions
Each validation function sets an error code if there's an error, and it has to return an array of valid values (possibly with prettifications and reformatting) if there's no error. These validation functions were written (for the most part) before this validation script or article existed. They've been tested for years to make sure that the validation script is of production quality.
Note that the actual return values of all of them are arrays; it's possible for some to return more than one value in the array, such as with email()
for email addresses. Also note that the return value might not be an array if there has been an error code set.
zip | Validation macro to define for a field for the zip values, either five digits or nine digits; as with other macros, it recognizes several variants, including spaces or no spaces, and with the case of a zip code, an optional hyphen. It is possible for multiple zip codes to be verified. |
---|---|
tel | Telephone numbers, including long distance and country codes, and all kinds of separators. |
cardno | Checks any common type of credit card number. |
text | Checks that text (this does not mean alphabetical characters only) is present. |
words | Checks that at least two words of text are present. |
Validates all kinds of email addresses. It is possible for multiple email addresses to be validated. | |
expires | checks a four-digit expiration date, that it has not expired, and that it is not an invalid amount into the future (using the computer's own clock, which is occasionally mis-set, resulting in errors, but this is OK, since the customers will be allowed to judge for themselves after receiving one warning). |
url | Matches the wide range of possible URL values. Of course, it is possible that a URL may point to a non-existent location. It may return multiple values. |