Form Validation
Javascript can be used to validate forms; however after implementing an re-implementing a number of variations on the theme I decided to produce a standard library which could be used anywhere.
The idea was to use the principles of unobtrusive javascript to develop a generic form validation method which would require as little configuration as possible to validate the most common HTML forms.
As usul on this site, I will show the results before I describe how it works, therefore, below is a form which implements my validation script.
Configuration
In order to configure the form for validation, each field requiring validation must be given one or more classes. The classes and their meanings are detailed below.
- "required" indicates a field is a required field. The form cannot be submitted until all fields with a class of required have a value. This can be combined with other validation classes.
- "decimal" indicates a field can only contain integer numbers. This is implemented by trapping the key press event and discarding any invalid keys.
- "numeric" similar to decimal, but allows floating point numbers.
- "email" only allows valid email addresses to be entered. The form cannot be submitted if an invalid address is entered.
- "date" indicates a field can only accept date values. This is the most complex validation option, any works in two modes, depending on the input field type. If the field type="hidden", a calendar is constructed and placed where the hidden field appears. However, if a normal text input is used, a popup calendar is created . In addition to the popup calendar, the users can type directly in the edit box and the date will be determined.
- "upper" indicates a field can only have uppercase alpha numerics entered.
- "lower" indicates a field can only have lowecase alpha numerics entered. This and upper are implemented purely by CSS.
In addition to setting the class of the form elements, the only other requirement is that each element must have a label assocated with it. This is used in any validation messages shown to the user.
Last updated: 12 Mar 2008 20:15:56