FormValidation.js Documentation

Key Object Initializers
Validator(label) A constructor for Validator objects.
initFormValidation() This function initializes the validation methods for the page's form.
initFormData(form) Defines form field manipulation methods and assigns them to the global formdata object.
Formatting Functions
formatInteger(value) Formats a value to a positive integer string.
formatSignedInteger(value) Formats a value to a signed integer string.
formatDecimal(value) Formats a value to a positive decimal string.
formatSignedDecimal(value) Formats a value to a signed decimal string.
formatCurrency(value) Formats a value to a positive currency string ($##,###).
formatSignedCurrency(value) Formats a value to a signed currency string.
formatPhone(value) Formats a value to a phone number string with area code (###-###-####).
formatSSN(value) Formats a value to a SSN number string (###-##-####).
formatPostal(value) Formats a value to a postal code string (##### or #####-####).
formatEmail(value) Formats a value to a valid email string.
formatDate(value) Formats a value to a valid date string (mm/dd/yyyy).
Parsing Functions
parseInteger(value) This method parses a string into an integer value.
parseSignedInteger(value) As parseInteger(), but allows negative integers as well.
parseDecimal(value) This method parses a string into a decimal value.
parseSignedDecimal(value) As parseDecimal(), but allows negative values as well.
parseCurrency(value) This method parses currency into a decimal value.
parseSignedCurrency(value) As parseCurrency(), but allows negative values as well.
parseDate(value) This method parses a string into a date value.
stripNonNumeric(value) This method strips the value of any non-numeric characters.
stripNonDecimal(value) This method strips the value of any non-decimal characters.
Get/SetValue Methods
text_getValue() A getValue() method for the various text form elements (text, password, file and hidden fields, as well as text areas).
text_setValue(value) A setValue() method for the various text form elements (text, password, file and hidden fields, as well as text areas).
select_getValue() A getValue() method for select lists.
select_getText() A getText() method for select lists.
select_setValue(value) A setValue() method for select lists.
checkbox_getValue() A getValue() method for checkboxes.
checkbox_setValue(value) A setValue() method for checkboxes.
group_getValue() A getValue() method for radio button groups.
group_setValue(value) A setValue() method for radio button groups.
radio_getValue() A getValue() method for individual radio buttons.
radio_setValue(value) A setValue() method for individual radio buttons.
Validation Functions
checkRequired(field) Checks whether a given field is (a) required and (b) missing.
checkRange(field) Checks whether a given field is within the specified range for that field.
checkLength(field) Checks whether the length of a given field is within the specified range for that field.
field_format() A method for formatting a form field using the format method in the field's associated Validator object.
field_parse() A method for parsing a form field using the parse method in the field's associated Validator object.
field_validate() A standard validation method for fields.
form_validate() A standard validation method for forms.
Form Initialization Functions
FormIterator(form) A constructor for creating an iterator for walking through form elements with validations.
goToNextEditableField(field) A function that moves the cursor from the given element to the next editable (not readonly) field.
initFieldValidation(field) This function assigns form validiation properties and methods to a field during form initialization.
Field Index Functions
indexInForm(field) A function for determining an element's index within its form.
indexInGroup(field) A function for determining an element's index within its group of elements with the same name.
nonRadioIndex(field) A function for determining a non-radio button's index within its group of elements with the same name.
radioIndex(field) A function for determining a radio button's index within its radio button group.
isFirstRadioButton(field) A function for determining the first radio button in a group.
isNotFirstRadioButton(field) A function for determining if the field is a radio button but not the first button in its group.


Key Object Initializers

The section has the definitions of the constructors and initializaters for the key objects created by this library:




Validator(label)

A constructor for Validator objects. It should be assigned to a validations property whose name matches the field being validated. Any validation properties for that field should be assigned to this object:

   // Example validations for an amount field:
   validations.amount = new Validator("Item Amount");
   validations.amount.datatype = "Integer";
   validations.amount.compute = computeTotals;
A Validator object is a prerequisite for setting validations for a field. The properties and methods assigned to Validator objects are copied to their corresponding field elements. In addition, each field is assigned a label property matching the parameter passed to its Validator constructor.
   // The validations copied to the amount field:
   document.form.amount.label = "Item Amount";
   document.form.amount.datatype = "Integer";
   document.form.amount.compute = computeTotals;


Parameters:
label - A human readable label for the field.

initFormValidation()

This function initializes the validation methods for the page's form. This function should be called in the onload event handler of the <BODY> tag:

   <body onload="initFormValidation()">
More specifically, this function: Of these operations, the initFormData() is the most fundamental.


initFormData(form)

Defines form field manipulation methods and assigns them to the global formdata object. There are multiple sets of methods, one set for each field in the form:

In each case, Field is replaced by the field's capitalized name. The last two methods are only present if the field has a matching method (compute and getText). All field manipulation methods can be called through the global formdata object. For example:
   formdata.setField(x);
This method is roughly equivalent to:
   document.form.field.setValue(x);
For text fields, it is roughly equivalent to:
   document.form.field.value = x;
If the form includes repeated groups of non-radio button elements, this method also initializes a formitems array. Each item in this array is like a formdata object for the element group. For example, to set the value for the Field with index i in the group:
   formitems[i].setField(value);


Parameters:
form - The form whose fields are added to the formdata object.
Formatting Functions

These functions format field values. Each field is assigned the formatting function appropriate to its data type as a method. Each method reformats the contents of the field value in a way appropriate to the data type. Each method returns the formatted value or an error string. The error string is always in the form "ERROR:message".


formatInteger(value)

Formats a value to a positive integer string. It is assigned to fields with data type "Integer".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The integer string or an error string if the formatting failed.

formatSignedInteger(value)

Formats a value to a signed integer string. It is assigned to fields with data type "SignedInteger".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The integer string or an error string if the formatting failed.

formatDecimal(value)

Formats a value to a positive decimal string. It is assigned to fields with data type "Decimal". Decimal fields may have an optional scale property, indicating the number of places after the decimal point. For example, a decimal field with a precision of 3 will always be formatted #.###. Missing values are filled with 0's. Excess values are rounded.

   validations.field.scale = #;


Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The decimal string or an error string if the formatting failed.

formatSignedDecimal(value)

Formats a value to a signed decimal string. It is assigned to fields with data type "SignedDecimal".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The decimal string or an error string if the formatting failed.

formatCurrency(value)

Formats a value to a positive currency string ($##,###). It is assigned to fields with data type "Currency".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The currency string or an error string if the formatting failed.

formatSignedCurrency(value)

Formats a value to a signed currency string. It is assigned to fields with data type "SignedCurrency".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The currency string or an error string if the formatting failed.

formatPhone(value)

Formats a value to a phone number string with area code (###-###-####). It is assigned to fields with data type "Phone".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The phone string or an error string if the formatting failed.

formatSSN(value)

Formats a value to a SSN number string (###-##-####). It is assigned to fields with data type "SSN".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The SSN string or an error string if the formatting failed.

formatPostal(value)

Formats a value to a postal code string (##### or #####-####). It is assigned to fields with data type "Postal".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The postal string or an error string if the formatting failed.

formatEmail(value)

Formats a value to a valid email string. It is assigned to fields with data type "Email".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The email string or an error string if the formatting failed.

formatDate(value)

Formats a value to a valid date string (mm/dd/yyyy). It is assigned to fields with data type "Date".

Parameters:
value - The value to be formatted. When assigned as a validation method, the field's value is used as the parameter for this method, and that value is reset to the result of this method.
Returns:
The date string or an error string if the formatting failed.
Parsing Functions

These methods parse string values into various data types. They are used primarily to parse the values of form fields. Each field is assigned the parsing function appropriate to its data type. The parsing methods return a value of NaN if the value passed to the method does not parse to the desired value.


parseInteger(value)

This method parses a string into an integer value. It is more forgiving than Javascript's standard parseInt() method because it ignores all non-decimal characters in the string. This method returns a positive integer. To allow negative integers, use parseSignedInteger() instead.

Parameters:
value - The value to be parsed.
Returns:
The positive integer value of the string, or NaN if the string contains no numbers.

parseSignedInteger(value)

As parseInteger(), but allows negative integers as well. This is not the default because for most applications, allowing negative values can lead to unexpected results and possibly security violations.

Parameters:
value - The value to be parsed.
Returns:
The signed integer value of the string, or NaN if the string contains no numbers.

parseDecimal(value)

This method parses a string into a decimal value. It is more forgiving than Javascript's standard parseFloat() method because it ignores all non-decimal characters in the string. This method returns a positive number. To allow negative numbers, use parseSignedDecimal() instead.

Parameters:
value - The value to be parsed.
Returns:
The positive decimal value of the string, or NaN if the string contains no numbers.

parseSignedDecimal(value)

As parseDecimal(), but allows negative values as well. This is not the default because for most applications, allowing negative values can lead to unexpected results and possibly security violations.

Parameters:
value - The value to be parsed.
Returns:
The signed decimal value of the string, or NaN if the string contains no numbers.

parseCurrency(value)

This method parses currency into a decimal value.

Parameters:
value - The value to be parsed.
Returns:
The positive decimal value of the string, or NaN if the string contains no numbers.

parseSignedCurrency(value)

As parseCurrency(), but allows negative values as well. This is not the default because for most applications, allowing negative values can lead to unexpected results and possibly security violations.

Parameters:
value - The value to be parsed.
Returns:
The signed decimal value of the string, or NaN if the string contains no numbers.

parseDate(value)

This method parses a string into a date value. It is less forgiving than Javascript's standard Date.parse() method because it does not allow illegal date combinations like "2/31/1999". It also has better Y2K compliance, converting 2 digit years to a date within 70 years in the past of the current date, or 30 years in the future.

Parameters:
value - The value to be parsed. If the value is already a Date() object, this method returns that object.
Returns:
The date as a Javascript Date, or NaN if the date is invalid.

stripNonNumeric(value)

This method strips the value of any non-numeric characters. It is useful for the preliminary formatting of such fields as Social Security Numbers, Postal Codes and Phone Numbers.

Parameters:
value - The value to be stripped.
Returns:
The string with all non-numeric characters stripped.

stripNonDecimal(value)

This method strips the value of any non-decimal characters. In particular, it retains only "." and the values "0" to "9". It is a useful preliminary for parsing of integer and decimal values.

Parameters:
value - The value to be stripped.
Returns:
The string with all non-decimal characters stripped.
Get/SetValue Methods

These methods get and set form field values. There is a different method for each type of form element. Each field in the form is assigned getValue() and setValue() methods appropriate to its type during the form's initialization (see the initFormValidation() method for additional details). These methods provide an object-oriented wrapper for manipulating field values in a consistent way. In particular, the following methods work as expected regardless of the field's actual type:

  var value = document.form.field.getValue(); 
  document.form.field.setValue(value);



text_getValue()

A getValue() method for the various text form elements (text, password, file and hidden fields, as well as text areas).

Returns:
The field value.

text_setValue(value)

A setValue() method for the various text form elements (text, password, file and hidden fields, as well as text areas).

Parameters:
value - The value to which the field is set.

select_getValue()

A getValue() method for select lists.

Returns:
The value of the currently selected option, or an empty string if none is selected.

select_getText()

A getText() method for select lists.

Returns:
The text of the currently selected option, or an empty string if none is selected.

select_setValue(value)

A setValue() method for select lists. The option whose value matches the parameter is selected. If there is no matching value, the list is set so that no option is selected.

Parameters:
value - The value to which the field is set.

checkbox_getValue()

A getValue() method for checkboxes.

Returns:
The value of the checkbox if selected, or an empty string if not selected.

checkbox_setValue(value)

A setValue() method for checkboxes. Selects the checkbox if the value parameter is equivalent to true, and deselects the checkbox is the parameter is equivalent to false (e.g. null, 0 or an empty string).

Parameters:
value - Whether to select this checkbox.

group_getValue()

A getValue() method for radio button groups.

Returns:
The value of the currently selected button, or an empty string if none is selected.

group_setValue(value)

A setValue() method for radio button groups. The button whose value matches the parameter is selected. If there is no matching value, no button is selected.

Parameters:
value - The value to which the field is set.

radio_getValue()

A getValue() method for individual radio buttons. It calls the getValue() method of its group.

Returns:
The value of the currently selected button, or an empty string if none is selected.

radio_setValue(value)

A setValue() method for individual radio buttons. It calls the setValue() method of its group.

Parameters:
value - The value to which the field is set.
Validation Functions

These functions are for validating fields. They are initialized when the page is loaded, and will be called automatically when the field value changes or during form submission.


checkRequired(field)

Checks whether a given field is (a) required and (b) missing. If so, it returns an error message. A field is marked required as follows:

   validations.field.required = true;


Parameters:
field - The field being validated.
Returns:
An error string if a required field is missing and an empty string otherwise. The error string is in a form suitable for inclusion in a list of missing fields.

checkRange(field)

Checks whether a given field is within the specified range for that field. If no range is specified, the field always passes this test. The range for a field is set as follows:

   validations.field.min = #;
   validations.field.max = #;
Either the max or the min may be omitted if there is no upper and lower bound. The max and min values are included in the allowed range.

Parameters:
field - The field being validated.
Returns:
An error string if a field is out of its allowed range.

checkLength(field)

Checks whether the length of a given field is within the specified range for that field. If no range is specified, the field always passes this test. The range for a field's length is set as follows:

   validations.field.minlength = #;
   validations.field.maxlength = #;
Either the max or the min may be omitted if there is no upper and lower bound. The max and min lengths are included in the allowed range. It may seem that the maxlength property duplicates the MAXLENGTH attribute of HTML text fields. It is not completely redundant, because: For example, in most browsers a text field's MAXLENGTH attribute is checked if the user types the entered characters, but not if the user pastes the characters into the field.

Parameters:
field - The field being validated.
Returns:
An error string if a field text's length is out of its allowed range.

field_format()

A method for formatting a form field using the format method in the field's associated Validator object.

Returns:
An empty string, or an error string if formatting failed. Unlike the underlying formatType method, the error string is not preceded by "ERROR:" and is suitable for display to the user.

field_parse()

A method for parsing a form field using the parse method in the field's associated Validator object.

Returns:
The parse value of the field, or NaN if the field value does not parse correctly. The "error value" of NaN is true for all data types, including dates.

field_validate()

A standard validation method for fields. This method is assigned to all form elements during form initialization. It is called each time the field value changes: the "onchange" event for text fields, the "onblur" event select lists, and the "onclick" event for checkboxes and radio buttons. This function calls the following standard validating functions:

If any errors are returned by these methods, the errors are displayed to the user in an alert and the form's focus returns to this element.


form_validate()

A standard validation method for forms. This method is assigned to the form during its initialization. It is called when the form is submitted. This function calls iterates through all the form's fields using a FormIterator. For each field, it calls the following standard validating functions:

This method also calls the following form method: If any errors are returned by these methods, the errors are displayed to the user in an alert, and the form submission is canceled.

Returns:
true if the field is valid, false otherwise.
Form Initialization Functions

These functions are used to initialize all the other validation functions in this script.


FormIterator(form)

A constructor for creating an iterator for walking through form elements with validations. This iterator has two methods:

The iterator is used as follows:
   i = form.getIterator();
   while (i.hasNext()) {
     var field = i.next();
// Work with each field
   }


Parameters:
form - The form to iterate through.

goToNextEditableField(field)

A function that moves the cursor from the given element to the next editable (not readonly) field. It is assigned to the onfocus event handler for read-only fields.

Parameters:
eter - field The field with the current focus.

initFieldValidation(field)

This function assigns form validiation properties and methods to a field during form initialization. In particular, it copies the validation properties and methods assigned to the matching Validator in the validations collection to the field.

   // Example validations for an amount field:
   validations.amount = new Validator("Item Amount");
   validations.amount.datatype = "Integer";
   validations.amount.compute = computeTotals;
  
   ...
  
   // The validations copied to the amount field:
   document.form.amount.label = "Item Amount";
   document.form.amount.datatype = "Integer";
   document.form.amount.compute = computeTotals;
In addition, the field will be assigned getter, setter and validate methods appropriate to the field's type. The assignments are: Finally, the following methods are called to format the field and perform multi-field computations, if these methods are present: Note that format functions will be assigned automatically for fields with known datatypes. Any validation errors that occur during initialization are suppressed.

Parameters:
field - The field to be initialized.
Field Index Functions

These methods return information about the index of a field element within its form or the group of elements with the same name.


indexInForm(field)

A function for determining an element's index within its form.

Parameters:
field - The field being checked.
Returns:
The index of the element within its form.

indexInGroup(field)

A function for determining an element's index within its group of elements with the same name.

Parameters:
field - The field being checked.
Returns:
The index of the element within its group, or -1 if the element is not in a group.

nonRadioIndex(field)

A function for determining a non-radio button's index within its group of elements with the same name.

Parameters:
field - The field being checked.
Returns:
The index of a non-radio button within its group, or -1 if (a) the element is not in a group or (b) the field is a radio button.

radioIndex(field)

A function for determining a radio button's index within its radio button group.

Parameters:
field - The field being checked.
Returns:
The index of a radio button within its group, or -1 if the field is not a radio button.

isFirstRadioButton(field)

A function for determining the first radio button in a group.

Parameters:
field - The field being checked.
Returns:
true if this is the first radio button in a group of radio buttons. This means it returns false if the field is not a radio button at all.

isNotFirstRadioButton(field)

A function for determining if the field is a radio button but not the first button in its group.

Parameters:
field - The field being checked.
Returns:
true if the field is a radio button, but not the first radio button of its group. This value is not necessarily the same as !isFirstRadioButton(field).