LiveValidation

Validation as you type!

Documentation...

This documentation is only concerned with the code you will actually need to know, all methods used internally are omitted, but they are all documented in the source code.

Contents


Validate (class) Top

The Validate class contains a number of static methods which are used to perform various types of validation. These are separated out from the LiveValidation class so they can be used in any context in your javascript, not just while validating form fields.

When you add a validation to a LiveValidation object, it is one of these validation types that you refer to, so familiarise yourself with them. If you are already familiar with Ruby on Rails validation, then they will be easy to remember, as they use a similar naming convention, and similar parameters (although some parameter’s names are different due to javascript keyword conflicts).

If used separately from a LiveValidation, and a validation fails, a custom error is thrown which stores the failure message, so you will need to handle this yourself if you wish to use the message. If you just want a simple true or false, and don't need to extract the failure message, you can use the Validate.now method to perform the validation.

Presence (static function) Top

Validates that a value is present (ie. not null, undefined, or an empty string)

Arguments:

value - {mixed} - value to be checked
paramsObj (optional) - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Can’t be empty!”)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Presence( 'hello world', { failureMessage: "Supply a value!" } );

Format (static function) Top

Validates a value against a regular expression

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Not valid!”)
pattern - {RegExp} - regular expression to validate against (DEFAULT: /./i)
negate - {Boolean} - if true will be valid if the value DOES NOT match the regular expression (DEFAULT: false)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

// check that 'validation' exists in the string, case insensitive...
Validate.Format( 'live validation', { pattern: /validation/i, failureMessage: "Failed!" } );

Numericality (static function) Top

Validates that the value is numeric and: is an integer, is a specific number, is more than a minimum number, less than a maximum number, is within a range of numbers, or a combination of these

NB - numbers expressed in scientific form (ie 2e3, being 2000) are handled correctly, as are negative numbers, and floats.

Arguments:

value - {mixed} - value to be checked
paramsObj (optional) - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

notANumberMessage (optional) - {String} - message to be used when validation fails because value is not a number (DEFAULT: “Must be a number!”)
notAnIntegerMessage (optional) - {String} - message to be used when validation fails because value is not an integer (DEFAULT: “Must be an integer!”)
wrongNumberMessage (optional) - {String} - message to be used when validation fails when ‘is’ param is used (DEFAULT: “Must be {is}!”)
tooLowMessage (optional) - {String} - message to be used when validation fails when ‘minimum’} param is used (DEFAULT: “Must not be less than {minimum}!”)
tooHighMessage (optional) - {String} - message to be used when validation fails when ‘maximum’} param is used (DEFAULT: “Must not be more than {maximum}!”)
is (optional) - {mixed} - the value must be equal to this numeric value
minimum (optional) - {mixed} - the minimum numeric allowed
maximum (optional) - {mixed} - the maximum numeric allowed
onlyInteger (optional) - {Boolean} - if true will only allow integers to be valid (DEFAULT: false)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

// check that value is an integer between -5 and 2000 exists in the string, case insensitive...
Validate.Numericality( 2e3, { minimum: -5, maximum: 2000 } );

Length (static function) Top

Validates the length of a value is a particular length, is more than a minimum, less than a maximum, or between a range of lengths

NB - to check if it is within a range, specify both a minimum and a maximum

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

wrongLengthMessage (optional) - {String} - message to be used when validation fails when ‘is’ param is used (DEFAULT: “Must be {is} characters long!”)
tooShortMessage (optional) - {String} - message to be used when validation fails when ‘minimum’} param is used (DEFAULT: “Must not be less than {minimum} characters long!”)
tooLongMessage (optional) - {String} - message to be used when validation fails when ‘maximum’} param is used (DEFAULT: “Must not be more than {maximum} characters long!”)
is (optional) - {mixed} - the value must be this length
minimum (optional) - {mixed} - the minimum length allowed
maximum (optional) - {mixed} - the maximum length allowed

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

// check that value is between 3 and 255 characters long...
Validate.Length( 'cow', { minimum: 3, maximum: 255 } );

Inclusion (static function) Top

Validates that a value falls within a given set of values

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Must be included in the list!”)
within - {Array} - an array of values that the value should fall in (DEFAULT: Empty array)
allowNull (optional) - {Boolean} - if true, and a null value is passed in, validates as true (DEFAULT: false)
partialMatch (optional) - {Boolean}- if true, will not only validate against the whole value to check, but also if it is a substring of the value (DEFAULT: false)
caseSensitive (optional) - {Boolean} - if false will compare strings case insensitively(DEFAULT: true)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Inclusion( 'cat', { within: [ 'cow', 277, 'catdog' ], allowNull: true, partialMatch: true, caseSensitive: false } );

Exclusion (static function) Top

Validates that a value does not fall within a given set of values

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Must not be included in the list!”)
within - {Array} - an array of values that the given value should not fall in (DEFAULT: Empty array)
allowNull (optional) - {Boolean} - if true, and a null value is passed in, validates as true (DEFAULT: false)
partialMatch (optional) - {Boolean} - if true, will not only validate against the whole value to check, but also if it is a substring of the value (DEFAULT: false)
caseSensitive (optional) - {Boolean} - if false will compare strings case insensitively(DEFAULT: true)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Exclusion( 'pig', { within: [ 'cow', 277, 'catdog' ], allowNull: true, partialMatch: true, caseSensitive: false } );

Acceptance (static function) Top

Validates that a value equates to true (for use primarily in detemining if a checkbox has been checked)

Arguments:

value - {mixed} - value to be checked
paramsObj (optional) - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Must be accepted!”)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Acceptance( true, { failureMessage: "You must be true!" } );

Confirmation (static function) Top

Validates that a value matches that of a given form field

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Does not match!”)
match -{mixed} - a reference to, or string id of the field that this should match

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Confirmation( 'open sesame', { match: 'myPasswordField', failureMessage: "Your passwords don't match!" } );

Email (static function) Top

Validates a value is a valid email address

This is an example of a custom validation method. This one is essentially just a Format validation, but one that is used often enough to merit its own method so that you don’t need to keep remembering the same crazy regular expression and failure message. You may want to mimic this to create your own re-useable validations, such as phone numbers, postcodes etc.

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Must be a valid email address!”)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

Validate.Email( 'live@validation.com', { failureMessage: "I am an overridden message!" } );

Custom (static function) Top

Validates a value against a custom function that returns true when valid or false when not valid.

You can use this to easily wrap any special validations that are not covered by the core ones, in a way that the LiveValidation class can use to give the feedback, without having to worry about the details.

Arguments:

value - {mixed} - value to be checked
paramsObj - {Object} - object containing parameters to be used for the validation

Parameters for paramsObj:

against - {Function} - a function that will take the value and an object of arguments and return true or false(DEFAULT: function( value, args ){ return true; } )
args - {Object} - an object of named arguments that will be passed to the custom function so are accessible through this object (DEFAULT: Empty object)
failureMessage (optional) - {String} - message to be used upon validation failure (DEFAULT: “Not valid!”)

Returns:

true if valid or throws a Validate.Error object containing the failure message

Example:

// Pass a function that checks if a number is divisible by one that you pass it in args object
// In this case, 5 is passed, so should return true and validation will pass
Validate.Custom( 55, { against: function(value,args){ return !(value % args.divisibleBy) }, args: {divisibleBy: 5} } );

now (static function) Top

Validates a passed in value using the passed in validation function, and handles the validation error for you so it gives a nice true or false reply

Arguments:

validationFunction - {Function} - reference to the validation function to be used (ie Validate.Presence )
value - {mixed} - value to be checked
validationParamsObj - {Object} - object containing parameters to be used for the validation (optional depends upon the validation function)

Returns:

true if valid or false if not valid

Example:

Validate.now( Validate.Numericality, '2007', { is: 2007 } );

LiveValidation (class)

The LiveValidation class sets up a text, checkbox, file, or password input, or a textarea to allow its value to be validated in real-time based upon the validations you assign to it.

constructor Top

The constructor of the LiveValidation class to set up the form field as a LiveValidation object allows you to pass in any parameters you want to override.

Arguments:

element - {mixed} - either a dom element reference or the string id of the element to validate
optionsObj (optional) - {Object} - object containing options to override the LiveValidation defaults

Parameters for paramsObj:

validMessage (optional) - {String} - message to be used upon successful validation (DEFAULT: “Thankyou!”)
onValid (optional) - {Function} - function to execute when field passes validation (DEFAULT: function(){ this.insertMessage( this.createMessageSpan() ); this.addFieldClass(); } )
onInvalid (optional) - {Function} - function to execute when field fails validation (DEFAULT: function(){ this.insertMessage( this.createMessageSpan() ); this.addFieldClass(); })
insertAfterWhatNode (optional) - {mixed} - reference or id of node to have the message inserted after (DEFAULT: the field that is being validated)
onlyOnBlur (optional) - {Boolean} - whether you want it to validate as you type or only on blur (DEFAULT: false)
wait (optional) - {Integer} - the time you want it to pause from the last keystroke before it validates (milliseconds) (DEFAULT: 0)
onlyOnSubmit (optional) - {Boolean} - if it is part of a form, whether you want it to validate it only when the form is submitted (DEFAULT: false)

Returns:

The LiveValidation object itself so that calls can be chained

Example:

var myField = new LiveValidation('myField', { validMessage: "I am valid!", onlyOnBlur: true });

add (function) Top

Validates a passed in value using the passed in validation function, and handles the validation error for you so it gives a nice true or false reply.

Arguments:

validationFunction - {Function} - reference to the validation function to be used (ie Validate.Presence )
validationParamsObj - {Object} - object containing parameters to be used for the validation (optional depends upon the validation function)

Returns:

The LiveValidation object itself so that calls can be chained

Example:

var myField = new LiveValidation('myField', { validMessage: "I am valid!" });
myField.add(Validate.Format, { pattern: /^hello$/i });

remove (function) Top

Removes a specific validation from the stack of validations that have been added

Note - you must pass it EXACTLY the same arguments as you used to add the validation

This is useful when writing custom code that alters validations based on whatever else may be happening on your webpage

Arguments:

validationFunction - {Function} - reference to the validation function being used (ie Validate.Presence )
validationParamsObj - {Object} - object containing parameters beeing used for the validation (optional depends upon whether used when the validation was added)

Returns:

The LiveValidation object itself so that calls can be chained

Example:

var myField = new LiveValidation('myField');
// add a Format and Length validation
myField.add(Validate.Format, { minimum: /^woohoo+$/ }).add(Validate.Length, {maximum: 20});
// now remove only the Format validation 
myField.remove(Validate.Format, { minimum: /^woohoo+$/ });

disable (function) Top

A helper to disable a field, so that validations are not run on it, and its value will not be posted if part of a form. It will also remove any previous validation message and field class.

This is useful for forms which can have different fields filled in depending upon choices they are given.

Returns:

The LiveValidation object itself so that calls can be chained

Example:

var myField = new LiveValidation('myField');
// disable the field - validations will not be run on this field, and its contents not submitted
myfield.disable();

enable (function) Top

A helper to enable a disabled field.

Will cause validations to be performed on the field again, after having been previously disabled.

Returns:

The LiveValidation object itself so that calls can be chained

Example:

var myField = new LiveValidation('myField');
// disable the field - validations will not be run on this field
myfield.disable();
// enable the field again - validations will now be run again
myField.enable();

destroy (function) Top

Will unregister all events of the LiveValidation object (preserving previously defined events) and remove it from any LiveValidationForm it might belong to.

This is useful if you don’t want a field to be a LiveValidation field any longer, or need to redefine a field as a new LiveValidation object with different parameters.

Example:

var myField = new LiveValidation('myField');
myfield.destroy();

massValidate (static function) Top

Pass an array of LiveValidation objects and it will validate all of them and return whether they pass or fail as a group

Note - as of release 1.2 it is unlikely you will ever need to use this function, as validation of all fields in a form on submission is now handled automatically.

Arguments:

validations - {Array} - an array of LiveValidation objects

Returns:

true if all the validations pass, false if any fail

Example:

// pass in an array of LiveValidation objects...
var areAllValid = LiveValidation.massValidate( [ obj1, obj2 ] );

LiveValidationForm (class)

If a LiveValidation field belongs to a form, that form will be automatically turned into a LiveValidationForm. This will handle making all LiveValidation fields that are part of it run validations when the form is submitted, and stop the form being sent if any are invalid.

destroy (function) Top

Will unregister all events of the LiveValidationForm object (preserving previously defined events), but only if there are no more LiveValidation objects belonging to it (unless forced to do so)

It is probably rare that you will need to use this as it is done automatically when LiveValidation objects are destroyed, but is useful for tests.

Arguments:

force - {Boolean} - whether to force the destruction even if it has child LiveValidation objects

Example:

var myField = new LiveValidation('myField');
// access the LiveValidationForm object through one of its child LiveValidation objects form property
myfield.form.destroy(true);


© 2007-2010 Alec Hill | MIT license

Share / bookmark this page