A css-class based form validation system.
| Mootools | Moo.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 |
| CNET | optional: <Fx.SmoothShow.js> |
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)
| form. validator.js | A css-class based form validation system. |
| InputValidator | This class contains functionality to test a field for various criteria and also to generate an error message when that test fails. |
| Properties | |
| test | Tests a field against the validator’s rule(s). |
| getError | Retrieves the error message for the validator. |
| 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. |
| 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 | |
| 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. |
| test | Tests a field against a specific validator. |
| resetField | Removes all the error messages for a specific field. |
| 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. |
| enforceField | Resumes validating a particular field |
| validators | An array of <Validator> objects. |
| add | Adds a new form validator to the FormValidator object. |
| addAllThese | An array of InputValidator configurations (see FormValidator.add above). |
| Included InputValidators | Here are the validators that are included in this libary. |
| Properties | |
| IsEmpty | Evalutes if the input is empty; this is a utility validator, see <FormValidator.required>. |
| required | Displays an error if the field is empty. |
| minLength | Displays a message if the input value is less than the supplied length. |
| maxLength | Displays a message if the input value is less than the supplied length. |
| validate-number | Validates that the entry is a number. |
| validate-digits | Validates that the entry contains only numbers |
| validate-alpha | Validates that the entry contains only letters |
| validate-alphanum | Validates that the entry is letters and numbers only |
| validate-date | Validates that the entry parses to a date. |
| validate-email | Validates that the entry is a valid email address. |
| validate-url | Validates that the entry is a valid url |
| validate-date-au | Validates that the entry matches dd/mm/yyyy. |
| validate-currency-dollar | |
| validate-one-required | Validates 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 * |
This class contains functionality to test a field for various criteria and also to generate an error message when that test fails.
| className | a className that this field will be related to (see example below); |
| options | an object with name/value pairs. |
| errorMsg | a message to display; see section below for details. |
| test | a function that returns true or false |
The errorMsg option can be any of the following
| string | the message to display if the field fails validation |
| boolean false | do not display a message at all |
| function | a 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) |
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.
//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)
| Properties | |
| test | Tests a field against the validator’s rule(s). |
| getError | Retrieves the error message for the validator. |
Tests a field against the validator’s rule(s).
| field | the form input to test |
| true | the field passes the test |
| false | it does not pass the test |
Retrieves the error message for the validator.
| field | the form input to test |
The error message or the boolean false if no message is meant to be returned.
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.
| form | the form to evaluate |
| options | an object with name/value pairs |
| fieldSelectors | the selector for fields to include in the validation; defaults to: “input, select, textarea” |
| useTitles | use the titles of inputs for the error message; overrides the messages defined in the InputValidators (see InputValidator); defaults to false |
| evaluateOnSubmit | validate the form when the user submits it; defaults to true |
| evaluateFieldsOnBlur | validate the fields when the blur event fires; defaults to true |
| evaluateFieldsOnChange | validate 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: “ |
| onFormValidate | function 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 |
| onElementValidate | function 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 |
(start code)var myFormValidator = new FormValidator($(‘myForm’), { onFormValidate: myFormHandler, useTitles: true });(end)
| 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 | |
| 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. |
| test | Tests a field against a specific validator. |
| resetField | Removes all the error messages for a specific field. |
| 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. |
| enforceField | Resumes validating a particular field |
| validators | An array of <Validator> objects. |
| add | Adds a new form validator to the FormValidator object. |
| addAllThese | An array of InputValidator configurations (see FormValidator.add above). |
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.
Validates all the inputs in the form; note that this function is called on submit unless you specify otherwise in the options.
Validates the value of a field against all the validators.
| field | the input element to evaluate |
| force | (boolean; optional) if false (or undefined) and options.serial==true, the validation does not occur |
Tests a field against a specific validator.
| className | the className associated with the validator |
| field | the 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. |
Stops validating the form; form will submit even if there are values that do not pass validation;
Stops validating a particular field.
| field | the field to ignore |
| warn | (boolean, optional) don’t require the validator to pass, but do produce a warning. |
Adds a new form validator to the FormValidator object.
| className | the className associated with the validator |
| options | the <Validator> options (errorMsg and test) |
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.
//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');
}
});
An array of InputValidator configurations (see FormValidator.add above).
FormValidator.addAllThese([
['className1', {errorMsg: ..., test: ...}],
['className2', {errorMsg: ..., test: ...}],
['className3', {errorMsg: ..., test: ...}],
]);
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.
| Properties | |
| IsEmpty | Evalutes if the input is empty; this is a utility validator, see <FormValidator.required>. |
| required | Displays an error if the field is empty. |
| minLength | Displays a message if the input value is less than the supplied length. |
| maxLength | Displays a message if the input value is less than the supplied length. |
| validate-number | Validates that the entry is a number. |
| validate-digits | Validates that the entry contains only numbers |
| validate-alpha | Validates that the entry contains only letters |
| validate-alphanum | Validates that the entry is letters and numbers only |
| validate-date | Validates that the entry parses to a date. |
| validate-email | Validates that the entry is a valid email address. |
| validate-url | Validates that the entry is a valid url |
| validate-date-au | Validates that the entry matches dd/mm/yyyy. |
| validate-currency-dollar | |
| validate-one-required | Validates that all the entries within the same node are not empty. |
Evalutes if the input is empty; this is a utility validator, see <FormValidator.required>.
| Error Msg | returns false (no message) |
Displays a message if the input value is less than the supplied length.
| Error Msg | Please enter at least [defined minLength] characters (you entered [input length] characters) |
You must add this className AND properties for it to your input.
<input type="text" name="username" class="minLength props{minLength:10}" id="username">Displays a message if the input value is less than the supplied length.
| Error Msg | Please enter no more than [defined maxLength] characters (you entered [input length] characters) |
You must add this className AND properties for it to your input.
<input type="text" name="username" class="maxLength props{maxLength:100}" id="username">Validates that the entry is a number.
| Error Msg | ’Please enter a valid number in this field.’ |
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.’ |
Validates that the entry contains only letters
| Error Msg | ’Please use letters only (a-z) in this field.’ |
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.’ |
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.’ |
Validates that the entry is a valid email address.
| Error Msg | ’Please enter a valid email address. For example fred@domain.com .’ |
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.’ |
| Error Msg | ’Please enter a valid $ amount. For example $100.00 .’ |
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.’ |
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.
<div>
<input ....>
<input ....>
<input .... className="validate-one-required">
</div>(end)
$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 *
returns the element passed in with all the Element prototypes applied.
function $( el )