jQuery Form Validator plugin

Update

Latest update to v. 1.1 to enhance compatibility with the newest jQuery v. 1.3.1.

Overview

The jQuery Form Validator plugin allows to define simple, yet powerful, validators for web pages forms. It's simple and configurable, and allows the definition of basic validations (required fields, numeric fields, integer fields, email fields) and also of regex over the fields in the forms.

Download

You can now download v. 1.1 of the jQuery Form Validator plugin.

Demo

On this web site you can find a working demo of the plugin.

Requirements

This plugin requires jQuery to be used in the web page. It has been tested with jQuery v. 1.2.6 and v. 1.3.1, but should correctly work with jQuery v. 1.2.x/1.3.1+.

Compatibility

The plugin has been tested on Windows XP, Windows Vista, Ubuntu (7.04, 7.10, 8.04 and 8.10) and Mac OS X 10.5 and is fully supported (at least) on the following browsers:

  • IE 8 beta, 7 & 6
  • Firefox 2.0+ and 3.0+
  • Opera 9 and 9.5+
  • Safari 3+
  • Google Chrome

Usage

The usage of the Form Validator is really simple. Example following:

var formValidator = new ValidatorClass();
formValidator.init({
form:           "#myFormID",
isRequired:     ['login', 'password'],
bindElement:    '#button',
callback:       function() {
alert('Ok!');
}
});

What it does

The method init() in the ValidatorClass instance enables the validator on the form with id="myFormID". Two text fields are required (those whose names are login and password).

The validator binds the object with id="button" to the 'click' event: when it's clicked, the validator runs the validation over the form. If the validation is successful, the callback function is called, otherwise an alert will popup telling which fields are wrong; those fields will also be coloured using a particular convention (red=required, green=numeric, blue=integer, yellow=email, lightgray=regex).

Complete example

The complete example for the script is:

var formValidator = new ValidatorClass();
formValidator.init({
form: '#example',
errorColors: {
isRequired: 'red',
isEmail:    'yellow',
isNumeric:  'green',
isInteger:  'blue',
hasRegex:   'lightgray'
},
isRequired:         ['name','email','number', 'date@select',
'street@select', 'description@textarea'],
isEmail:            ['email'],
isNumeric:          ['number'],
isInteger:          ['integer'],
hasRegex:           [
['field1', /d./, 'Error message'],
['field2@textarea', /s{5}(d{5}s{5}){1,10}$/, 'Another error']
],
allowNullNumbers:   true,
requiredFieldMsg:   'I campi in rosso sono obbligatori',
emailFieldMsg:      'I campi in giallo devono essere email',
numericFieldMsg:    'I campi in verde devono contenere numeri',
integerFieldMsg:    'I campi in blu devono contenere valori interi',
bindElement:        ['#button1', '#button2'],
bindEvent:          'click',
callback:           [callBack1, callBack2],
});

function callBack1() {
// Do something ...
}

function callBack2() {
// Do something different ...
}

Please note the definition of the required fields: for the five validation types it is possible to define an array of the field to control. Each item can be expressed in two forms:

  1. 'fieldName', which is equivalent to the CSS selector: input[name=fieldName]
  2. 'fieldName@domType', which is equivalent to the CSS selector: domType[name=fieldName] (es. domType = textarea)

Parameters

This is the explanation for every single parameter passed to the method. The default values are expressed in the square brackets next to the name:

  • form: the id of the form that will have the validation enabled
  • errorColor: a hash variable containing these colors for the wrong fields (colors applied to the fields after the validation):
    • isRequired['#FDD']: the CSS color that the field will have if it's required and not filled
    • isEmail['#FFA']: the CSS color that the field will have if it has an incorrect email
    • isNumeric['#DFD']: the CSS color that the field will have if it's not a number
    • isInteger['#CCE']: the CSS color that the field will have if it's not an integer number
    • hasRegex['#CCC']: the CSS color that the field will have if it's not compatible with the regex
  • isRequired: an array with the names of the fields that are required
  • isEmail: an array with the names of the fields that must be valid emails
  • isNumeric: an array with the names of the fields that must be numeric
  • isInteger: an array with the names of the fields that must have integer values
  • hasRegex: an array of arrays defining the regexes. Each inner array is in the form ['fieldName', /regex/, 'Error message']
  • allowNullNumbers[false]: if it is set to 'true' it allows numeric and integer field to have no values without being considered wrong
  • font-weight: bold;">requiredFieldMsg['Red fields are required']: the alert message for required fields
  • emailFieldMsg['Yellow fields must contain valid emails']: the alert message for the email fields
  • numericFieldMsg['Green fields must contain numbers']: the alert message for the numeric fields
  • integerFieldMsg['Blue fields must contain integer values']: the alert message for the integer fields
  • bindElement: an array of the id's of the objects to which the validator will be bound
  • bindEvent['click']: the event for which the validator will be bound to the previous elements
  • callback: an array of the functions to be called if the validation is successful. Each callback function is related to a single element: i.e. callBack1 is the callback function for '#button1', etc.

API

  • init(): initializes the validator (read above for the parameters to be passed)
  • reset(): without any parameter, disables the validator

Terms of use

The jQuery Form Validator plugin is licensed under a Creative Commons License and is copyrighted (C)2008-2010 by Daniele Di Bernardo.

The license page can be found at: http://creativecommons.org/licenses/by-nc-sa/2.5/it/

One thought on “jQuery Form Validator plugin

  1. Molto utile, davvero. Secondo me andrebbe implementato un ulteriore metodo, sulla falsa riga di hasRegex, del tipo "checkAjax" che richiama uno script esterno per il controllo della form.

    checkAjax: [['field', 'script.php', 'Error message'], [...]]

    Può essere utile ad esempio per i campi di tipo "codice fiscale" che prevedono uno script che magari esiste già in una qualche funzione di php, oppure semplicemente un controllo via db sull'elenco di opzioni lecite per un determinato campo.

    Ciao
    A.

Lascia un Commento

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *

È possibile utilizzare questi tag ed attributi XHTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>