SAMPLE CODE FOR
FORM VALIDATION
Form validation is one of the most common uses for JavaScript.
JavaScript is a quick, easy way to check a user's input for mistakes, typos,
and the omission of required fields. Because validation takes place on
the client machine, there's no delay for contacting a remote server. The
user gets quicker responses, and network bandwidth and server processing
power are both conserved. Developers will find it easier and more intuitive
to do form validation with JavaScript than with CGI scripts.
This sample demonstrates the use of JavaScript to validate
two forms. There are six files in this directory (plus three Navigator
2.02 versions):
To use this sample code, first try using the USform.htm
and Intlform.htm samples. See how the forms
make sure that the user enters data into the required fields (marked with
asterisks) and check the data the user enters into some fields (like phone
numbers and credit cards).
Next, View Source on the forms to see the commented HTML source for the
forms and methods like onChange which call functions to check the data.
Next, read the commented source code for FormChek.js
to see the library of JavaScript functions which are used to validate the
data. You can put this JavaScript file into your own applications and reuse
the functions it contains.
If you decide to change the source code of FormChek.js,
use the test suite test.htm to make sure that its
functions still work as expected after your changes.
The header of FormChek.js, included below, lists
and briefly explains all of the functions provided by the library. For
detailed information, see the comments for each function in the source.
NAVIGATOR VERSIONS COMPATIBILITY
NOTE
The source code in FormChek.js has been tested
on Windows 95 with Netscape Navigator 2.02 and 3.01Gold and Netscape Communicator
Preview Release 3. It is compatible with all three versions. The only difference
between the Navigator 2.02 demos and the main demos is the inclusion of
the JavaScript source code within the HTML file. JavaScript 1.0 for Navigator
2.02 does not support the SRC= attribute of the SCRIPT tag, so it is not
possible to place the JavaScript source code in an external file; the JavaScript
source code must be placed within the HTML file in a SCRIPT tag in the
HEAD.
Bottom line: if you must create forms which are backwardly compatible with
Netscape Navigator 2.02, place the JavaScript source code in the HTML file
in a SCRIPT tag in the HEAD. But if you only have to support Navigator
3.01Gold and later, place the JavaScript source code in an external file
and import it into the HTML file using the SRC= attribute of the SCRIPT
tag. This will make it possible to share a single JavaScript source file
among many HTML files, easing long-term maintenance.
HEADER OF SOURCE
CODE FILE FormChek.js
// FormChek.js
//
// SUMMARY
//
// This is a set of JavaScript functions for validating input on
// an HTML form. Functions are provided to validate:
//
// - U.S. and international phone/fax numbers
// - U.S. ZIP codes (5 or 9 digit postal codes)
// - U.S. Postal Codes (2 letter abbreviations for names of states)
// - U.S. Social Security Numbers (abbreviated as SSNs)
// - email addresses
// - dates (entry of year, month, and day and validity of combined date)
// - credit card numbers
//
// Supporting utility functions validate that:
//
// - characters are Letter, Digit, or LetterOrDigit
// - strings are a Signed, Positive, Negative, Nonpositive, or
// Nonnegative integer
// - strings are a Float or a SignedFloat
// - strings are Alphabetic, Alphanumeric, or Whitespace
// - strings contain an integer within a specified range
//
// Functions are also provided to interactively check the
// above kinds of data and prompt the user if they have
// been entered incorrectly.
//
// Other utility functions are provided to:
//
// - remove from a string characters which are/are not
// in a "bag" of selected characters
// - reformat a string, adding delimiter characters
// - strip whitespace/leading whitespace from a string
// - reformat U.S. phone numbers, ZIP codes, and Social
// Security numbers
//
//
// Many of the below functions take an optional parameter eok (for "emptyOK")
// which determines whether the empty string will return true or false.
// Default behavior is controlled by global variable defaultEmptyOK.
//
// BASIC DATA VALIDATION FUNCTIONS:
//
// isWhitespace (s) Check whether string s is empty or whitespace.
// isLetter (c) Check whether character c is an English letter
// isDigit (c) Check whether character c is a digit
// isLetterOrDigit (c) Check whether character c is a letter or digit.
// isInteger (s [,eok]) True if all characters in string s are numbers.
// isSignedInteger (s [,eok]) True if all characters in string s are numbers; leading + or - allowed.
// isPositiveInteger (s [,eok]) True if string s is an integer > 0.
// isNonnegativeInteger (s [,eok]) True if string s is an integer >= 0.
// isNegativeInteger (s [,eok]) True if s is an integer < 0.
// isNonpositiveInteger (s [,eok]) True if s is an integer <= 0.
// isFloat (s [,eok]) True if string s is an unsigned floating point (real) number. (Integers also OK.)
// isSignedFloat (s [,eok]) True if string s is a floating point number; leading + or - allowed. (Integers also OK.)
// isAlphabetic (s [,eok]) True if string s is English letters
// isAlphanumeric (s [,eok]) True if string s is English letters and numbers only.
//
// isSSN (s [,eok]) True if string s is a valid U.S. Social Security Number.
// isUSPhoneNumber (s [,eok]) True if string s is a valid U.S. Phone Number.
// isInternationalPhoneNumber (s [,eok]) True if string s is a valid international phone number.
// isZIPCode (s [,eok]) True if string s is a valid U.S. ZIP code.
// isStateCode (s [,eok]) True if string s is a valid U.S. Postal Code
// isEmail (s [,eok]) True if string s is a valid email address.
// isYear (s [,eok]) True if string s is a valid Year number.
// isIntegerInRange (s, a, b [,eok]) True if string s is an integer between a and b, inclusive.
// isMonth (s [,eok]) True if string s is a valid month between 1 and 12.
// isDay (s [,eok]) True if string s is a valid day between 1 and 31.
// daysInFebruary (year) Returns number of days in February of that year.
// isDate (year, month, day) True if string arguments form a valid date.
// FUNCTIONS TO REFORMAT DATA:
//
// stripCharsInBag (s, bag) Removes all characters in string bag from string s.
// stripCharsNotInBag (s, bag) Removes all characters NOT in string bag from string s.
// stripWhitespace (s) Removes all whitespace characters from s.
// stripInitialWhitespace (s) Removes initial (leading) whitespace characters from s.
// reformat (TARGETSTRING, STRING, Function for inserting formatting characters or
// INTEGER, STRING, INTEGER ... ) delimiters into TARGETSTRING.
// reformatZIPCode (ZIPString) If 9 digits, inserts separator hyphen.
// reformatSSN (SSN) Reformats as 123-45-6789.
// reformatUSPhone (USPhone) Reformats as (123) 456-789.
// FUNCTIONS TO PROMPT USER:
//
// prompt (s) Display prompt string s in status bar.
// promptEntry (s) Display data entry prompt string s in status bar.
// warnEmpty (theField, s) Notify user that required field theField is empty.
// warnInvalid (theField, s) Notify user that contents of field theField are invalid.
// FUNCTIONS TO INTERACTIVELY CHECK FIELD CONTENTS:
//
// checkString (theField, s [,eok]) Check that theField.value is not empty or all whitespace.
// checkStateCode (theField) Check that theField.value is a valid U.S. state code.
// checkZIPCode (theField [,eok]) Check that theField.value is a valid ZIP code.
// checkUSPhone (theField [,eok]) Check that theField.value is a valid US Phone.
// checkInternationalPhone (theField [,eok]) Check that theField.value is a valid International Phone.
// checkEmail (theField [,eok]) Check that theField.value is a valid Email.
// checkSSN (theField [,eok]) Check that theField.value is a valid SSN.
// checkYear (theField [,eok]) Check that theField.value is a valid Year.
// checkMonth (theField [,eok]) Check that theField.value is a valid Month.
// checkDay (theField [,eok]) Check that theField.value is a valid Day.
// checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
// Check that field values form a valid date.
// getRadioButtonValue (radio) Get checked value from radio button.
// checkCreditCard (radio, theField) Validate credit card info.
// CREDIT CARD DATA VALIDATION FUNCTIONS
//
// isCreditCard (st) True if credit card number passes the Luhn Mod-10 test.
// isVisa (cc) True if string cc is a valid VISA number.
// isMasterCard (cc) True if string cc is a valid MasterCard number.
// isAmericanExpress (cc) True if string cc is a valid American Express number.
// isDinersClub (cc) True if string cc is a valid Diner's Club number.
// isCarteBlanche (cc) True if string cc is a valid Carte Blanche number.
// isDiscover (cc) True if string cc is a valid Discover card number.
// isEnRoute (cc) True if string cc is a valid enRoute card number.
// isJCB (cc) True if string cc is a valid JCB card number.
// isAnyCard (cc) True if string cc is a valid card number for any of the accepted types.
// isCardMatch (Type, Number) True if Number is valid for credic card of type Type.
//
// Other stub functions are retained for backward compatibility with LivePayment code.
// See comments below for details.
//
// 18 Feb 97 created
//
// (c) 1997 Netscape Communications Corporation