matt's multi-language validation script

version 2.2

This script may be re-used and distributed freely provided this header remains intact and all supporting files are included in the distribution. All documentation and code in this distribution is provided as is with no warranty of any kind. Direct any issues or requests to matthew.frank@mindspring.com. If you use the script, please send me an email with the URL of the site if it is public. I will endeavor to keep you updated to future releases.

NOTE: This script only runs (i.e. has been tested) on x86 client platforms running Windows 95/NT 4.0 and Microsoft Internet Explorer 4.01 and greater.

Supported Languages
en English (default)
de German
fr French
pt Portuguese
es Spanish
it Italian
nl Dutch

When included properly in a page, this script initializes all methods and functions required to perform validation on any and all forms within the page, at the discretion of the page's author. It works by checking each form object within the document for an attribute of validate. If this attribute is found, the script generates the necessary event handlers (onsubmit, onreset) for the form, but also captures the current event handlers (if they exist). If validate="onchange", the script will also capture and set onchange event handlers for all form elements within the given form. (Note that your onsubmit/onreset functions will run AFTER the validation performed by this script.) This initialization is automatically performed when the browser is done parsing the page. If you subsequently add more forms or form elements, simply call the setup() method of the _validation object to process the new objects. It is important to note that manipulating the validate attribute at run-time has no effect on the validation of the form.

To validate individual form fields, you will need to insert attributes for each field. All attributes are case-insensitive. A failed validation check will change the className of the form field to invalid. You will need to specify a style for this class in order to make an effect apparent. You may also specify a color with the invalidColor attribute for the script to use in place of a className (e.g. invalidColor="yellow"). I have found a bug in IE4 that does not allow SELECT elements to use the className change effectively; in this case, I recommend using the invalidColor attribute.

You may customize the error message generated by providing your own message: msg="This is my error message." This attribute is especially pertinent for use with regular expression validation.

This script should be included with the defer attribute to ensure that the whole page is parsed prior to running the script. I bypassed the body.onload event purposely to allow custom scripting of that event. If you have difficulties using the defer attribute, simply place the script as the last element on the document (just before </BODY>). Or you can include the script on any page to simply load it into the client's cache. Paste the following line into each page requiring validation:

<SCRIPT defer src="PATH_TO_SCRIPT/validation.js" type="text/javascript"></SCRIPT>

View a sample form that incorporates this validation script.


The following list of attributes define and modify the types of validation provided. To incorporate a given attribute, include it in the text of the HTML object:

<FORM validate="onchange" lang="de" mark>
Supported Attributes
Attribute Object Description
default Element If the field does not contain a value when the form is submitted, this value will be inserted automatically. This is different from the defaultValue property available through the document object model.
filter Element Only the specified key characters are accepted as input. Characters are specified as regular expressions (e.g. [a-zA-Z ] means all characters and spaces; \d means all digits)
insert Form Used in combination with the mark attribute, this property specifies the HTML text which will be inserted to mark required fields.
invalidColor Form, Element The given field will adopt this color when it is invalid. This attribute overrides the use the invalid className. If you intend to perform validation on SELECT elements, use this attribute as there is a bug in IE4 relating to assigning classNames via script (discovered in Win95; IE 4.01 SP1).
lang All Language definition for a given HTML element (HTML 4.0)
mark Form This FORM attribute tells the script to mark all required fields by one of two means. If the page designer specifies a value for the insert attribute, the contents of the insert attribute are inserted before or after the field, depending on the value specified for mark ("before" or "after"). By default, fields are marked by changing their className to "required" (which requires a style be defined for that class). Note that the use of other classes for form elements is impaired when implementing this option.
msg Element A custom-defined error message for a given field
notrim Form Disables the automatic trim of leading and trailing whitespace from element values within a given form
nym Element Defines the display name for a given form element
onmark Element Pseudo-event which runs directly before a field is marked via the markRequired method; returning false prevents the marking of the field. Since this is not a true event, the event object is not available for scripting.
onvalidate Element Pseudo-event which runs directly after all default validation for a given form field. Accepts string or function types. Use this event to trigger validation on SELECT elements. Since this is not a true event, the event object is not available for scripting.
onvalidatefocus Element Pseudo-event which runs directly before failed validation gives focus back to the element. The event cannot be cancelled. Use this event to make the field visible before it tries to get focus.
pivot Form, Element Defines the pivot year (must be 2 digits) for all date fields on a given form: all two-digit years (xx) coming before this number are translated to 20xx; all other two-digit years are translated to 19xx. If the attribute is applied to a specific form element, its definition overrides the pivot year defined on the form.
ssi Form Allows inclusion of Server Side Include text. Otherwise all SSI text is changed to HTML comments
validate Form Causes the script to perform field-level validation on all the elements of a given FORM. Set to "onchange" to force validation prior to exiting individual fields that have been changed (this validation is in addition to that performed when the form is submitted). This property is read at the time of initial setup; setting or changing its value at run-time has no effect.
year4 Form Requires all date fields to have a 4 digit year within a given form

The following table lists the methods generated via the validation script. They are particularly useful for processing errors generated in the onvalidate pseudo-event. All methods are generated as the script loads and finish before the onload event is fired on the window. If you insert forms or elements through DHTML, run

_validation.setup();
to create the methods on the new objects.
Exposed Methods
Object Method Description Use
Element paint Sets style for a given form element to show that the field is invalid (class="invalid") oElement.paint();
restore Returns style of form element to the class before it was painted oElement.restore();
valid Returns true if the form element passes all validation checks defined on it; runs onvalidate event handler bBool = oElement.valid();
Err add Add error to Err object oErr.add( oElement, iType, sFormat );

oErr.add( oElement, sMessage, sFormat );

clear Remove all errors from the Err object oErr.clear();
raise Display popup message box with error(s) from Err object oErr.raise();
Form markRequired Marks all required fields of a form by setting class="required" or inserting HTML before or after the individual elements. oForm.markRequired();
String trim Returns the string with leading and trailing whitespace removed. sString1 = sString2.trim();
Validation isDate Returns true if the value of oElement is a date string with the format defined by sFormat bBool = oValidation.isDate( oElement, sFormat );
isNum Returns true if sValue is not empty (i.e., "") and contains only digits. bBool = oValidation.isNum( sValue );
setDefault Returns the default value (vDefault) if vValue does not have a valid value (e.g., null, undefined, ""). vVariant = oValidation.setDefault( vValue, vDefault );
setup Creates event handlers and methods for all forms and elements that have not already been processed. If you do not dynamically insert forms or elements into the page, this method is not of use. oValidation.setup();

The following attributes, when applied to form elements, are referenced from the valid method to determine if the value of the element is consistent with its edit checks. Note that none of the validation checks are mutually exclusive (i.e., date and integer on the same element will always yield an error for at least one of them).
<INPUT type="text" date="DD/MM/YYYY">
Supported Validation Checks
amount The field must contain a valid monetary amount. The value of the attribute (e.g., amount=".") specifies the decimal delimiter (e.g., 1234.56). The default value of the delimiter is "." and only "," may be used in its stead. This check assumes a currency with 1/100 units (e.g., the American penny).
and If the field contains a value, all the fields whose names appear in this comma-delimited list must also contain values.
date The field must contain a valid date as specified by the property (e.g. date="YYYY/MM/DD"). The default value for the date format is "MM/DD/YYYY". If the delimiter on the input data is different from the format specified, the script returns false. If the format does not contain a delimiter and the "MM", "DD", and "YYYY" tokens, the script will return false.
float The field must contain a valid floating point number. The value of the attribute (e.g., float=",") specifies the decimal delimiter (e.g., 5,689). The default delimiter value is "." and only "," may be used in its stead.
integer The field must contain a valid integer
lowercase All letters become lowercase.
mask Similar to the regexp check, the mask allows you to define an expected format for the given field. An x indicates a position held by a letter (case-insensitive); a 9 indicates a digit; z indicates an optional digit; a is any letter. Any other character is considered a literal and will be expected in the user's input exactly as it appears in the mask. For example, "$ZZ9.99" requires a dollar amount up to 999.99 with leading zeros suppressed.
nospace All whitespace is removed from the field
or If the field does not contain a value, at least one of the fields whose names appear in this comma-delimited list must contain a value. Use this validation on the default field for the group.
regexp The field value must be consistent with the given regular expression. This validation check is useful for edit masks that need to allow multiple or complex formats (e.g., a US ZIP code: ^\d{5}(-\d{4})?$). It is strongly recommended that you create a custom message (msg) for regexp fields.
required The field value must contain non-whitespace data
signed When used in combination with amount, float, or integer, this attribute further allows the user to use plus (+) or minus (-) sign in element.
uppercase All letters become uppercase.

Release Notes
1.0 Initial publication.
1.1
  • Added amount validation and custom error messages
  • Included use of nym attribute to allow further customization of error messages
1.2
  • Added language detection (lang attribute) to avoid re-typing custom error messages
  • Added mask and regexp validation
  • Added automated required field marking
  • Added auto-selection of invalid values
  • Added relational validation
  • Added conditional compilation to limit use of the script to tested platforms (subsequently removed)
  • Removed restriction that custom-defined onsubmit handlers require return values
2.0
  • All error handling is performed via object methods. These methods are exposed to the developer employing this script.
  • Optionally disable automatic trim of element values
  • Optionally require a 4 digit year
  • Add pivot year
  • Optionally disable automatic removal of SSI text
2.01
  • Fixed oForm.reset and oForm.submit naming problems
  • Optimized onvalidate processing
  • Fixed automation server error many clients were experiencing due to use of the "Scripting.Dictionary" ActiveXObject.
  • Recommended defer attribute on script include
2.02
  • Fixed onvalidate processing to run from valid() method
  • Expanded Err.add() to allow for customized error messages from code
2.1
  • Added onmark event
  • Changed the name of mark() method to markRequired() to alleviate name collisions with regard to the mark [Form] attribute.
  • Added insert, signed, and default attributes
  • Moved Err.clear() inside of Err.raise() to run automatically after displaying error(s)
  • Fixed mask to use "9" as digit, "x" as character, "a" as letter, and "z" as optional digit (thanks to my Cobol compatriots).
  • Required float/amount delimiter to be either "." or "," only.
2.11
  • Inserting HTML for required field marking drives on insert rather than mark
2.12
  • Fixed errors in MASK, FLOAT validation
2.2
  • Added onvalidatefocus event
  • Added keystroke filter
  • Added check for forms in setup so that script may be embedded in non-form pages
  • Minor fixes