form. validator.js

A css-class based form validation system.

Dependencies

MootoolsMoo.js, Utility.js, Common.js, Element.js, Function.js, Event.js, String.js, Fx.Base.js, Window.Base.js, Fx.Style.js, Fx.Styles.js, Dom.js
CNEToptional: <Fx.SmoothShow.js>

Authors

Aaron Newton, <aaron [dot] newton [at] cnet [dot] com> Based on validation.js by Andrew Tetlaw (http://tetlaw.id.au- /view- /blog- /really-easy-field-validation-with-prototype)

Summary
form. validator.jsA css-class based form validation system.
InputValidatorThis class contains functionality to test a field for various criteria and also to generate an error message when that test fails.
Properties
testTests a field against the validator’s rule(s).
getErrorRetrieves the error message for the validator.
FormValidatorEvalutes an entire form against all the validators that are set up, displaying messages and returning a true/false response for the evaluation of the entire form.
FormValidator must be configured with <Validator> objects; see below for details as well as a list of built-in validators.  Each <Validator> will be applied to any input that matches its className within the elements of the form that match the fieldSelectors option.Each <Validator> can also be used to generate warnings.
Properties
resetRemoves all the error messages from the form.
validateValidates all the inputs in the form; note that this function is called on submit unless you specify otherwise in the options.
validateFieldValidates the value of a field against all the validators.
testTests a field against a specific validator.
resetFieldRemoves all the error messages for a specific field.
stopStops validating the form; form will submit even if there are values that do not pass validation;
startResumes validating the form.
ignoreFieldStops validating a particular field.
enforceFieldResumes validating a particular field
validatorsAn array of <Validator> objects.
addAdds a new form validator to the FormValidator object.
addAllTheseAn array of InputValidator configurations (see FormValidator.add above).
Included InputValidatorsHere are the validators that are included in this libary.
Properties
IsEmptyEvalutes if the input is empty; this is a utility validator, see <FormValidator.required>.
requiredDisplays an error if the field is empty.
minLengthDisplays a message if the input value is less than the supplied length.
maxLengthDisplays a message if the input value is less than the supplied length.
validate-numberValidates that the entry is a number.
validate-digitsValidates that the entry contains only numbers
validate-alphaValidates that the entry contains only letters
validate-alphanumValidates that the entry is letters and numbers only
validate-dateValidates that the entry parses to a date.
validate-emailValidates that the entry is a valid email address.
validate-urlValidates that the entry is a valid url
validate-date-auValidates that the entry matches dd/mm/yyyy.
validate-currency-dollar
validate-one-requiredValidates that all the entries within the same node are not empty.
Change Log$Source: /cvs/main/flatfile/html/rb/js/global/cnet.global.framework/common/js.widgets/form.validator.js,v $ $Log: form.validator.js,v $ Revision 1.15 2007/06/02 01:35:56 newtona * empty log message *

InputValidator

This class contains functionality to test a field for various criteria and also to generate an error message when that test fails.

Arguments

classNamea className that this field will be related to (see example below);
optionsan object with name/value pairs.

Options

errorMsga message to display; see section below for details.
testa function that returns true or false

errorMsg

The errorMsg option can be any of the following

stringthe message to display if the field fails validation
boolean falsedo not display a message at all
functiona function to evaluate that returns either a string or false.  This function will be passed two parameters: the field being evaluated and any properties defined for the validator as a className (see examples below)

test

The test option is a function that will be passed the field being evaluated and any properties defined for the validator as a className (see example below); this function must return true or false.

Examples

//html code
<input type="text" name="firstName" class="required" id="firstName">
//simple validator
var isEmpty = new InputValidator('required', {
errorMsg: 'This field is required.',
test: function(field){
return ((element.getValue() == null) || (element.getValue().length == 0));
}
});
isEmpty.test($("firstName")); //true if empty
isEmpty.getError($("firstName")) //returns "This field is required."

//two complex validators
<input type="text" name="username" class="minLength maxLength" validatorProps="{minLength:10, maxLength:100}" id="username">

var minLength = new InputValidator ('minLength', {
errorMsg: function(element, props){
//props is {minLength:10, maxLength:100}
if($type(props.minLength))
return 'Please enter at least ' + props.minLength + ' characters (you entered ' + element.value.length + ' characters).';
else return '';
},
test: function(element, props) {
//if the value is >= than the minLength value, element passes test
return (element.value.length >= $pick(props.minLength, 0));
else return false;
}
});

minLength.test($('username'));

var maxLength = new InputValidator ('maxLength', {
errorMsg: function(element, props){
//props is {minLength:10, maxLength:100}
if($type(props.maxLength))
return 'Please enter no more than ' + props.maxLength + ' characters (you entered ' + element.value.length + ' characters).';
else return '';
},
test: function(element, props) {
//if the value is <= than the maxLength value, element passes test
return (element.value.length <= $pick(props.maxLength, 10000));
else return false;
}
});(end)
Summary
Properties
testTests a field against the validator’s rule(s).
getErrorRetrieves the error message for the validator.

Properties

test

Tests a field against the validator’s rule(s).

Arguments

fieldthe form input to test

Returns

truethe field passes the test
falseit does not pass the test

getError

Retrieves the error message for the validator.

Arguments

fieldthe form input to test

Returns

The error message or the boolean false if no message is meant to be returned.

FormValidator

Evalutes an entire form against all the validators that are set up, displaying messages and returning a true/false response for the evaluation of the entire form.

An instance of the FormValidator class will test each field and then behave according to the options passed in.

Arguments

formthe form to evaluate
optionsan object with name/value pairs

Options

fieldSelectorsthe selector for fields to include in the validation; defaults to: “input, select, textarea”
useTitlesuse the titles of inputs for the error message; overrides the messages defined in the InputValidators (see InputValidator); defaults to false
evaluateOnSubmitvalidate the form when the user submits it; defaults to true
evaluateFieldsOnBlurvalidate the fields when the blur event fires; defaults to true
evaluateFieldsOnChangevalidate the fields when the change event fires; defaults to true
serial(boolean) if one field fails validation, do not validate other fields unless their contents actually change (instead of on blur); defaults to true
warningPrefix(string) prefix to be added to every warning; defaults to “Warning: “
errorPrefix(string) prefix to be added to every error; defaults to “Error: “
onFormValidatefunction to execute when the form validation completes; this function is passed two arguments: a boolean (true if the form passed validation) and the form element
onElementValidatefunction to execute when an input element is tested; this function is passed two arguments: a boolean (true if the form passed validation) and the input element

Example

(start code)var myFormValidator = new FormValidator($(‘myForm’), { onFormValidate: myFormHandler, useTitles: true });(end)

Summary
FormValidator must be configured with <Validator> objects; see below for details as well as a list of built-in validators.  Each <Validator> will be applied to any input that matches its className within the elements of the form that match the fieldSelectors option.Each <Validator> can also be used to generate warnings.
Properties
resetRemoves all the error messages from the form.
validateValidates all the inputs in the form; note that this function is called on submit unless you specify otherwise in the options.
validateFieldValidates the value of a field against all the validators.
testTests a field against a specific validator.
resetFieldRemoves all the error messages for a specific field.
stopStops validating the form; form will submit even if there are values that do not pass validation;
startResumes validating the form.
ignoreFieldStops validating a particular field.
enforceFieldResumes validating a particular field
validatorsAn array of <Validator> objects.
addAdds a new form validator to the FormValidator object.
addAllTheseAn array of InputValidator configurations (see FormValidator.add above).

FormValidator must be configured with <Validator> objects; see below for details as well as a list of built-in validators.  Each <Validator> will be applied to any input that matches its className within the elements of the form that match the fieldSelectors option.

Using Warnings

Each <Validator> can also be used to generate warnings.  Warnings still show error messages, but do not prevent the form from being submitted.  Warnings can be applied in two ways. warn per validator - You can specify any validator as a warning by prefixing “warn-” to the class name.  So, for example, if you have a validator called “validate-numbers” you can add the class “warn-validate-numbers” and a warning will be offered rather than an error.  The validator will not prevent the form from submitting. warn per field - You can also ignore all the validators for a given field.  You can add the class “warnOnly” to set all it’s validators to present warnings only or you can add the class “ignoreValidation” to the field to turn all the validators off.  Note that the FormValidator class has methods do this for you: see FormValidator.ignoreField and FormValidator.enforceField.

Properties

reset

Removes all the error messages from the form.

validate

Validates all the inputs in the form; note that this function is called on submit unless you specify otherwise in the options.

validateField

Validates the value of a field against all the validators.

Arguments

fieldthe input element to evaluate
force(boolean; optional) if false (or undefined) and options.serial==true, the validation does not occur

test

Tests a field against a specific validator.

Arguments

classNamethe className associated with the validator
fieldthe input element
warn(boolean; optional) if set to true, test will add a warning advice message if the validator fails, but will always return valid regardless of the input.

resetField

Removes all the error messages for a specific field.

Arguments

fieldthe field to reset.

stop

Stops validating the form; form will submit even if there are values that do not pass validation;

start

Resumes validating the form.

ignoreField

Stops validating a particular field.

Arguments

fieldthe field to ignore
warn(boolean, optional) don’t require the validator to pass, but do produce a warning.

enforceField

Resumes validating a particular field

Arguments

fieldthe field to resume validating

validators

An array of <Validator> objects.

add

Adds a new form validator to the FormValidator object.

Arguments

classNamethe className associated with the validator
optionsthe <Validator> options (errorMsg and test)

Note

This method is a property of every instance of FormValidator as well as the FormValidator object itself.  That is to say that you can add validators to the FormValidator object or to an instance of it.  Adding validators to an instance of FormValidator will make those validators apply only to that instance, while adding them to the Class will make them available to all instances.

Examples

//add a validator for ALL instances
FormValidator.add('isEmpty', {
errorMsg: 'This field is required',
test: function(element){
if(element.value.length ==0) return false;
else return true;
}
});

//this validator is only available to this single instance
var myFormValidatorInstance = new FormValidator('myform');
myFormValidatorInstance.add('doesNotContainTheLetterQ', {
errorMsg: 'This field cannot contain the letter Q!',
test: function(element){
return !element.getValue().test('q','i');
}
});

//Extend FormValidator, add a global validator for all instances of that version
var NewFormValidator = FormValidator.extend({
//...some code
});
NewFormValidator.add('doesNotContainTheLetterZ', {
errorMsg: 'This field cannot contain the letter Z!',
test: function(element){
return !element.getValue().test('z','i');
}
});

addAllThese

An array of InputValidator configurations (see FormValidator.add above).

Example

FormValidator.addAllThese([
['className1', {errorMsg: ..., test: ...}],
['className2', {errorMsg: ..., test: ...}],
['className3', {errorMsg: ..., test: ...}],
]);

Included InputValidators

Here are the validators that are included in this libary.  Add the className to any input and then create a new FormValidator and these will automatically be applied.  See FormValidator.add on how to add your own.

Summary
Properties
IsEmptyEvalutes if the input is empty; this is a utility validator, see <FormValidator.required>.
requiredDisplays an error if the field is empty.
minLengthDisplays a message if the input value is less than the supplied length.
maxLengthDisplays a message if the input value is less than the supplied length.
validate-numberValidates that the entry is a number.
validate-digitsValidates that the entry contains only numbers
validate-alphaValidates that the entry contains only letters
validate-alphanumValidates that the entry is letters and numbers only
validate-dateValidates that the entry parses to a date.
validate-emailValidates that the entry is a valid email address.
validate-urlValidates that the entry is a valid url
validate-date-auValidates that the entry matches dd/mm/yyyy.
validate-currency-dollar
validate-one-requiredValidates that all the entries within the same node are not empty.

Properties

IsEmpty

Evalutes if the input is empty; this is a utility validator, see <FormValidator.required>.

Error Msgreturns false (no message)

required

Displays an error if the field is empty.

Error Msg”This field is required”

minLength

Displays a message if the input value is less than the supplied length.

Error MsgPlease enter at least [defined minLength] characters (you entered [input length] characters)

Note

You must add this className AND properties for it to your input.

Example

<input type="text" name="username" class="minLength props{minLength:10}" id="username">

maxLength

Displays a message if the input value is less than the supplied length.

Error MsgPlease enter no more than [defined maxLength] characters (you entered [input length] characters)

Note

You must add this className AND properties for it to your input.

Example

<input type="text" name="username" class="maxLength props{maxLength:100}" id="username">

validate-number

Validates that the entry is a number.

Error Msg’Please enter a valid number in this field.’

validate-digits

Validates that the entry contains only numbers

Error Msg’Please use numbers only in this field.  Please avoid spaces or other characters such as dots or commas.’

validate-alpha

Validates that the entry contains only letters

Error Msg’Please use letters only (a-z) in this field.’

validate-alphanum

Validates that the entry is letters and numbers only

Error Msg’Please use only letters (a-z) or numbers (0-9) only in this field.  No spaces or other characters are allowed.’

validate-date

Validates that the entry parses to a date.

Error Msg’Please use this date format: mm/dd/yyyy.  For example 03/17/2006 for the 17th of March, 2006.’

validate-email

Validates that the entry is a valid email address.

Error Msg’Please enter a valid email address.  For example fr.nosp@m.ed@domai.nosp@m.n.com .’

validate-url

Validates that the entry is a valid url

Error Msg’Please enter a valid URL.’

validate-date-au

Validates that the entry matches dd/mm/yyyy.

Error Msg’Please use this date format: dd/mm/yyyy.  For example 17/03/2006 for the 17th of March, 2006.’

validate-currency-dollar

Validates that the entry matches any of the following

  • [$]1[##][,###]+[.##]
  • [$]1###+[.##]
  • [$]0.##
  • [$].##
Error Msg’Please enter a valid $ amount.  For example $100.00 .’

validate-one-required

Validates that all the entries within the same node are not empty.

Error Msg’Please enter something for at least one of the above options.’

Note

This validator will get the parent element for the input and then check all its children.  To use this validator, enclose all the inputs you want to group in another element (doesn’t matter which); you only need apply this class to one of the elements.

Example

<div>
<input ....>
<input ....>
<input .... className="validate-one-required">
</div>(end)

Change Log

$Source: /cvs/main/flatfile/html/rb/js/global/cnet.global.framework/common/js.widgets/form.validator.js,v $ $Log: form.validator.js,v $ Revision 1.15 2007/06/02 01:35:56 newtona * empty log message *

Revision 1.14 2007/05/29 22:01:53 newtona Split element.cnet.js into seperate files; updated docs in files to note this Changed element.visible to element.isVisible (left old namespace for legacy support) Fixed Element.empty in prototype.compatibility.js Removed as many dependencies in common code to element.*.js as possible (espeically element.shortcuts.js)

Revision 1.13 2007/04/13 00:22:57 newtona fixed a typo in FormValidator.hideAdvice (display: none instead of display: block)

Revision 1.12 2007/04/06 00:43:51 newtona slight syntax update

Revision 1.11 2007/04/06 00:37:40 newtona tweaked the way serial works

Revision 1.10 2007/04/05 23:48:55 newtona FormValidator now has numerous new features: instance-level validators, .stop, .start, .ignoreField, .enforceField, and warnings

Revision 1.9 2007/04/05 23:01:26 newtona FormValidator now has numerous new features: instance-level validators, .stop, .start, .ignoreField, .enforceField, and warnings

Revision 1.8 2007/03/02 00:28:37 newtona advice is now inserted into the DOM in it’s own method so it can be easily overriden makeAdvice no longer inserts the advice.

Revision 1.7 2007/02/22 18:18:42 newtona typo in the docs

Revision 1.6 2007/02/07 20:51:41 newtona implemented Options class implemented Events class StickyWin now uses Element.position

Revision 1.5 2007/02/06 18:10:36 newtona updated the error displays to use the new element.smoothshow function

Revision 1.4 2007/02/03 01:36:17 newtona added multi-select support shortened validate-number updated validate-date essage and fixed a bug in it

Revision 1.3 2007/01/26 05:48:03 newtona docs update

Revision 1.2 2007/01/22 22:00:15 newtona numerous bug fixes to modalizer, stickywin, and popupdetails updated for mootools 1.0 fixed date validation in form.validator

Revision 1.1 2007/01/19 01:22:05 newtona * empty log message *

Adds a new form validator to the FormValidator object.
My Object Oriented javascript.
Contains Utility functions
Contains common implementations for custom classes.
function $(el)
returns the element passed in with all the Element prototypes applied.
Contains useful Element prototypes, to be used with the dollar function $.
Contains Function prototypes and utility functions .
Event class
Contains String prototypes and Number prototypes.
Base class for the Mootools Effects (Moo.Fx) library.
Contains Fx.Base and two Transitions.
Contains Window.onDomReady Authors:
The Style effect; Extends Fx.Base, inherits all its properties.
Contains Fx.Style
Allows you to animate multiple css properties at once; Extends Fx.Base, inherits all its properties.
Contains Fx.Styles
Custom class to allow all of its methods to be used with any DOM element via the dollar function $.
Css Query related function and Element extensions
This class contains functionality to test a field for various criteria and also to generate an error message when that test fails.
Stops validating a particular field.
Resumes validating a particular field
Evalutes an entire form against all the validators that are set up, displaying messages and returning a true/false response for the evaluation of the entire form.