CNET JS Code Documentation
Class: InputValidator
This class contains functionality to test a field for various criteria and also to generate an error message when that test fails.
Authors
- Aaron Newton
- Based on validation.js by Andrew Tetlaw
Implements
Syntax
new InputValidator(className, options);
Arguments
- className - (string) a className that this field will be related to (see example below)
- options - (object) a key/value set of options
Options
- errorMsg - (mixed) a message to display; see section below for details.
- test - (function) a function that returns true or false
Option: errorMsg
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)
Option: 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)); } });
InputValidator Method: test
Tests a field against the validator's rule(s).
Syntax
myInputValidator.test(field);
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the form input to test
Returns
- (boolean) - true if the field passes the test; false if it does not pass the test
InputValidator Method: getError
Retrieves the error message for the validator.
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the form input to test
Returns
- (mixed) - The error message (string) or boolean false if no message is meant to be returned.
Class: 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.
Implements
Syntax
new FormValidator(form[, options]);
Arguments
- form - (mixed) A string of the id for an Element or an Element reference of the form to evaluate
- options - (object) a key/value set of options
Options
- fieldSelectors - (string) the selector for fields to include in the validation; defaults to "input, select, textarea"; these are applied only to the children of the form
- useTitles - (boolean) use the titles of inputs for the error message; overrides the messages defined in the InputValidators (see InputValidator); defaults to false
- evaluateOnSubmit - (boolean) whether to validate the form when the user submits it; defaults to true
- evaluateFieldsOnBlur - (boolean) whether to validate the fields when the blur event fires; defaults to true
- evaluateFieldsOnChange - (boolean) whether to validate the fields when the change event fires; defaults to true
- serial - (boolean) whether to validate other fields if one field fails validation unless the other fields' contents actually change (instead of onblur); 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: "
Events
- onFormValidate - (function) callback to execute when the form validation completes; this function is passed three arguments: a boolean (true if the form passed validation); the form element; and the onsubmit event object if there was one (othewise, passed undefined)
- onElementValidate - (function) callback 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
var myFormValidator = new FormValidator($('myForm'), { onFormValidate: myFormHandler, useTitles: true });
Notes
- FormValidator must be configured with InputValidator objects (see below for details as well as a list of built-in validators). Each InputValidator will be applied to any input that matches its className within the elements of the form that match the fieldSelectors option.
Using Warnings
Each InputValidator 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.
FormValidator Method: reset
Removes all the error messages from the form.
Syntax
myFormValidator.reset();
Returns
- (object) - This instance of FormValidator
FormValidator Method: validate
Validates all the inputs in the form; note that this function is called on submit unless you specify otherwise in the options.
Syntax
myFormValidator.validate(event);
Arguments
- event - (event, optional) the submit event
Returns
- (boolean) true if all the form inputs pass validation
FormValidator Method: validateField
Validates the value of a field against all the validators.
Syntax
myFormValidator.validateField(field[, force]);
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the input element to evaluate
- force - (boolean, optional) whether to force validation; if false (or undefined) and options.serial==true, the validation does not occur
Returns
- (boolean) true if the form input passes validation
FormValidator Method: test
Tests a field against a specific validator.
Syntax
myFormValidator.test(className, field, warn);
Arguments
- className - (string) the className associated with the validator
- field - (mixed) A string of the id for an Element or an Element reference of the input element to test against the className/validator
- warn - (boolean, optional) whether test will add a warning advice message if the validator fails; if set to true test will always return valid regardless of the input.
Returns
- (boolean) true if the form input passes the specified validation
FormValidator Method: resetField
Removes all the error messages for a specific field.
Syntax
myFormValidator.resetField(field);
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the input element to reset
Returns
- (object) This instance of FormValidator
FormValidator Method: stop
Stops validating the form; when form is submitted, even if there are values that do not pass validation the submission will proceed.
Syntax
myFormValidator.stop();
Returns
- (object) This instance of FormValidator
FormValidator Method: start
Resumes validating the form.
Syntax
myFormValidator.start();
Returns
- (object) This instance of FormValidator
FormValidator Method: ignoreField {#FormValidator Method:ignoreField}
Stops validating a particular field.
Syntax
myFormValidator.ignoreField(field[, warn]);
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the input element to ignore
- warn - (boolean, optional) whether to produce a warning if the validtor does not pass; defaults to false
Returns
- (object) This instance of FormValidator
FormValidator Method: enforceField
Resumes validating a particular field
Syntax
myFormValidator.enforceField(field);
Arguments
- field - (mixed) A string of the id for an Element or an Element reference of the input element to resume validating
Returns
- (object) - This instance of FormValidator
Adding Custom Validators
FormValidator.js includes many default validators. You can add your own using these methods.
FormValidator Method: add
Adds a new form validator to the global FormValidator object or to an instance (see notes).
Syntax
//add a form validator to my instance myFormValidator.add(className, options); //add a form validator to all future instances (globally) FormValidator.add(className, options);
Arguments
- className - (string) the className associated with the validator
- options - (object) the InputValidator options (errorMsg and test)
Notes
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'); } });
FormValidator: addAllThese
An array of InputValidator configurations (see FormValidator.add above).
Syntax
//add several input validators to all instances of FormValidator FormValidator.addAllThese(validators); //add several input validators to a specific instance of FormValidator myFormValidator.addAllThese(validators);
Arguments
- validators - (array) an array of validators (see example below and FormValidator.add).
Example
FormValidator.addAllThese([ ['className1', {errorMsg: ..., test: ...}], ['className2', {errorMsg: ..., test: ...}], ['className3', {errorMsg: ..., test: ...}], // etc.. ]);
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.
Validator: IsEmpty
Evalutes if the input is empty; this is a utility validator, see FormValidator.required.
Validator: required
Displays an error if the field is empty.
Error Msg: "This field is required"
Validator: minLength
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)"
Note
You must add this className AND properties for it to your input.
Example
<input type="text" name="username" class="minLength" validatorProps="{minLength:10}" id="username"/>
Validator: maxLength
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)"
Note
You must add this className AND properties for it to your input.
Example
<input type="text" name="username" class="maxLength" validatorProps="{maxLength:10}" id="username"/>
Validator: validate-numeric
Validates that the entry is a number.
Error Msg: 'Please enter only numeric values in this field ("1" or "1.1" or "-1" or "-1.1").'
Validator: validate-integer
Validates that the entry is an integer.
Error Msg: "Please enter an integer in this field. Numbers with decimals (e.g. 1.25) are not permitted."
Validator: validate-digits
Validates that the entry contains only numbers but allows punctuation and spaces (for example, a phone number)
Error Msg: "Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas."
Validator: validate-alpha
Validates that the entry contains only letters
Error Msg - "Please use letters only (a-z) in this field."
Validator: 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."
Validator: validate-date
Validates that the entry parses to a date.
Error Msg: "Please enter a valid date (such as 12/31/1999)"
Validate: validate-email
Validates that the entry is a valid email address.
Error Msg: "Please enter a valid email address. For example 'fred@domain.com'."
Validate: validate-url
Validates that the entry is a valid url
Error Msg: "Please enter a valid URL."
Validator: 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 ."
Validator: 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>
Native: Element
Extends the native Element object (typically a form) with a reference to its validator instance.
Element property: validator
Syntax
myForm.retrieve('validator'); //the instance of form validator for the form