Menu

Advertisement supports Validation plugin and website, please disable your ads blocker

Learn how to use the JavaScript form validation wrapped in a jQuery plugin.

Installation

Set Bower to update the latest Validation version

$ bower install html5-form-validation#~1.5.3

Required

jQuery 1.7.2 and above because of .on event handler - Download

event handler - Download Latest Validation plugin - 1.5.3 - Download

Optional

bootstrap-popover-2.3.2 to display input helpers. (Requires Tooltip to also be included) - Download - Demo

<html> <head> ... <!-- Required --> <script src="/vendor/jquery/js/jquery-2.1.0.min.js"></script> <script src="/vendor/runningCoder/js/jquery.validation.min.js"></script> <!-- No debug inside .min file --> <!-- Optional - Helpers --> <script src="/vendor/bootstrap/js/bootstrap-tooltip-2.3.2.js"></script> <script src="/vendor/bootstrap/js/bootstrap-popover-2.3.2.js"></script> ... </head>

Initialization

There are 2 ways to initialize the form validation:

Create a jQuery object using a form selector and then chain .validate() function passing an optional object of parameters // Every forms on page $('form').validate({ submit: { settings: { display: 'block', allErrors: true trigger: 'mousedown' } } }); // One form $('form#myForm').validate({ submit: { settings: { clear: 'keypress' }, callback: { onError: function (error) { alert(error.toString()); } } } }); or Call the $.validate() function. In this case the configuration form will be required // Every forms on page $.validate({ submit: { settings: { form: 'form' ... } } }); // One form $.validate({ submit: { settings: { form: 'form#myform' ... }, callback: { ... } } });

Configuration

The configuration object will be merged with the default class configuration. The Validation is using Object.preventExtensions and a list of _supported options to prevent the object from receiving unsupported parameters.

/** * @private * Default options */ var _options = { submit: { settings: { form: null, display: "inline", insertion: "append", allErrors: false, trigger: "click", button: "[type='submit']", errorClass: "error", errorListClass: "error-list", errorListContainer: null, inputContainer: null, clear: "focusin", scrollToError: false }, callback: { onInit: null, onError: null, onBeforeSubmit: null, onSubmit: null, onAfterSubmit: null } }, dynamic: { settings: { trigger: null, delay: 300 }, callback: { onSuccess: null, onError: null, onComplete: null } }, debug: false }; /** * @private * Limit the supported options on matching keys */ var _supported = { submit: { settings: { display: ["inline", "block"], insertion: ["append", "prepend"], allErrors: [true, false], clear: ["focusin", "keypress", false], trigger: [ "click", "dblclick", "focusout", "hover", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "toggle" ] } }, dynamic: { settings: { trigger: [ "focusout", "keydown", "keypress", "keyup" ] } }, debug: [true, false] };

submit.settings

Option Type Description form {string} [optional] null (default) The jQuery form selector is only required if the validation was initialized without a jQuery object. In that case, if no form is found, the Validation is dropped. display {string} inline|block inline (default) Errors are displayed per field. block Creates a global container and every errors are displayed inside. insertion {string} append|prepend append (default) The error list will be appended to the input if display is inline or to the form if display is block prepend The error list will be prepended. allErrors {boolean} false (default) Only one error per field is displayed even if it contains multiple. true All errors are displayed. trigger {string} jQuery mouse event click (default) Event that will be delegated to button and trigger the form validation. The possible values are listed inside _supported.submit.trigger options above or you can also check jQuery mouse event for more details. button {string} input[type="submit"] (default) jQuery selector of the form submit button that will trigger the form Validation. errorClass {string} error (default) If an error is found after validating the input, the class will be applied to the input and it's associated label. <label class="error"> Username <input name="signup[username]" class="error"> </label> or <label for="signup-username" class="error">Username</label> <input name="signup[username]" id="signup-username" class="error"> errorListClass {string} error-list (default) If an error is found the error list container will receive this class. <div class="error-list" data-error-list=""> <ul> <li>Username must not be empty.</li> </ul> </div> errorListContainer {string} null (default) By default, the error container will be appended to the input's parent container. You can however change that using this option, the error container will be appended / prepended to the input's closest container. // errorListContainer: '.hello' // Error container will be appended / prepended inside .hello instead of the input's parent (label tag) <div class="hello"> <label class="error"> Username <input name="signup[username]" class="error"> </label> </div> inputContainer {string} [optional] null (default) jQuery selector of the block that contains the input and label. The errorClass will be added on this container if there is a Validation error. * In this example, ".control-group" is the inputContainer <div class="control-group" class="error"> <label class="control-label" for="inputPassword" class="error">Password</label> <div class="controls"> <input type="password" id="inputPassword" class="error"> </div> </div> clear {string|false} focusin (default) On an input focusin or keypress , the errorClass will be cleared. false The errorClass class will persist until the form is submitted again. scrollToError {boolean|object} false (default) This option accept an object with offset and duration in ms. If this option is set the page will scroll to the first error when the form gets validated or when using $(form).addError() . - Demo scrollToError: { offset: -100, duration: 500 }

dynamic.settings

Option Type Description trigger {string} [optional] null (default) Event that will be delegated to the input and trigger the it's validation. The possible values are listed inside _supported.dynamic.trigger options above or you can also check jQuery keyboard event for more details. * Be cautious if you are using keypress as the backspace will not trigger the validation since this is a part of jQuery itself, use keyup instead. delay {numeric} 300 (default) Time in milliseconds for the trigger to be fired. * In the eventuality of using keypress it is recommended to slightly increase the delay.

window.Validation

Option Type Description messages {object} [optional] This option is used to override every error message corresponding to the specified validation rule. * If you want to override only for a specified form, use $(form).validate({messages: {}) instead. //-- Global override -- Validation.messages = { 'NOTEMPTY': 'Overriding the global NOTEMPTY message' }; //-- Form override -- $('form').validate({ messages: { 'NOTEMPTY': 'Overriding the form\'s NOTEMPTY message' } }; labels {object} [optional] This option will override the inputName inside the error message. There are 3 ways of overriding: Global: Overrides every matching inputName on page

Initialization: Overrides every matching inputName inside the form

HTML Attribute: Overrides only the specified field //-- Global override -- Validation.labels = { 'contact_v1[email]': 'Custom label name from Configuration' }; //-- Initialization override -- $('form').validate({ labels: { 'contact_v1[email]': 'Custom label name from Initialization' } }; <!-- HTML Attribute override --> <input name="contact[username]" data-validation="[L>=2]" data-validation-label="This custom label from attribute">

Callbacks

The callbacks are used to customize and add functionalities to your form. You will find plenty of examples in the Demo section. The submit callbacks returns the node as the last parameter, the dynamic callbacks returns the node and the input as the last 2 parameters. The submit and dynamic onError callback also returns either the global error array or the input error array.

There are 3 ways to define the callbacks:

String

Function name (can be namespaced) located on the window scope without any parameters.

$('form#myForm').validate({ submit: { callback: { onInit: 'myFunction' } } }); or $('form#myForm').validate({ submit: { callback: { onInit: 'window.myCollection.myFunction.get' } } });

Array

First element is the function name located on the window scope, second element is an array containing the parameters.

$('form#myForm').validate({ dynamic: { settings: { trigger: "keyup" }, callback: { onError: ['myFunction', ['param1', 'param2']] } } }); window.myFunction = function (a, b, node, input, keyCode, errors) { console.log(a, b, node, input, keyCode, errors); };

Function

Anonymous function calling a local function with parameters.

$('form#myForm').validate({ submit: { callback: { onError: function (node, globalError) { console.log(node, globalError); } } } }); or $('form#myForm').validate({ dynamic: { settings: { trigger: "keyup" }, callback: { onSuccess: function (node, input, keyCode) { myFunction('param1', 'param2', node, input, keyCode) } } } }); function myFunction (a, b, node, input, keyCode) { console.log(a, b, node, input, keyCode); }

submit.callback (node, errors)

node jQuery object of the initialization form

jQuery object of the initialization form errors Array of errors only returned by onError callback only

Array of errors only returned by callback only formData Object containing all of the form data

Callback Description onInit (node) Will be executed on Validation initialization. onValidate (node) Will be executed after the submit.settings.button is triggered and before the Validation occurs. onError (node, errors) Will be executed if errors are found. onBeforeSubmit (node) Will be executed if no errors are found and before the form gets submitted. onSubmit (node, formData) Will be executed if no errors are found. * Careful, using this callback will override the native HTML form.submit() and prevent the form from submitting by default. onAfterSubmit (node) Will be executed if no errors are found and after the form gets submitted. * Some browser may not execute this function correctly as it's attempting to redirect after submit().

dynamic.callback (node, input, keyCode, errors)

node jQuery object of the initialization form

jQuery object of the initialization form input DOM of the input element that was validated

DOM of the input element that was validated keyCode The keyCode that was pressed when the validation was triggered or null if your trigger is focusout

The keyCode that was pressed when the validation was triggered or if your trigger is errors Array of errors only returned by onError callback

Callback Description onError (node, input, keyCode, errors) Will be executed if error(s) are found on the dynamic input. onSuccess (node, input, keyCode) Will be executed if no error(s) are found on the dynamic input. onComplete (node, input, keyCode) Will be executed regardless if error(s) were found on the dynamic input.

For more details about the callbacks execution see the flowcharts below or experience some of them on the Demo page.

HTML Attributes

Attribute Value Description data-validation {array} Contains a list of validation rules. See below for the complete list. If the field contains no data-validation or has disabled attribute, it will not be validated. <!-- Validates for alphanumeric and char length between 6 and 24 (inclusively) --> <input name="signup[username]" data-validation="[MIXED, L>=6, L<=24]"> data-validation-message {string} [optional] If it is not set, a generic error message will be displayed. * Using this attribute will only display 1 message for all of the rules defined in data-validation . * Using "$" inside the message serves as a placeholder for the input short name. Hint! You can output a variable that would contain the configuration text to display for translated errors. <!-- Translated error message --> <input name="signup[username]" data-validation="[MIXED, L>=6, L<=24]" data-validation-message="<?=$transErrorUsername;?>"> data-validation-regex data-validation-regex-message {regex} [optional] {string} [optional] Regular expression to validate against. If the data-validation-regex attribute is set, you must define a data-validation-regex-message or the default message will be displayed. * Only "/" is accepted as a valid regex delimiter. * Placing "$" inside the message will be replaced by the input short name. <!-- Username must not contain "admin", start or end by a digit --> <input name="signup[username]" data-validation-regex="/^(?![0-9])((?!admin).)*$/i" data-validation-regex-message="Word 'admin' is not allowed in $ ..."> data-validation-regex-reverse {boolean} [optional] Reverse the Regular expression lookup. If you do not know how to write the regex you are looking for, you easily reverse the lookup. <!-- Password must not contain "coca" or "cola" --> <input name="signup[username]" data-validation-regex="/(coca|cola)/i" data-validation-regex-reverse data-validation-regex-message="Word 'coca' or 'cola' is not allowed in $ ..."> <!-- Password must not contain "coca" or "cola" (without reverse) --> <input name="signup[username]" data-validation-regex="/^((?!coca|cola).)*$/i" data-validation-regex-message="Word 'coca' or 'cola' is not allowed in $ ..."> data-validation-label {string} [optional] Setting this attribute will override the inputName inside the error message. - Demo <!-- Replaces the inputName inside the error message --> <input name="signup[username]" data-validation="[L>=6, L<=24]" data-validation-label="Custom label name">

Validation Rules

These rules are used inside data-validation attribute formatted as an array.

Rules Regex Description NOTEMPTY /\S/ Field must contain at least a non-whitespace character. <!-- Search field must not be submitted empty --> <input name="search[text]" data-validation="[NOTEMPTY]"> INTEGER /^\d+$/ Validate for an integer value. NUMERIC /^\d+(?:[,\s]\d{3})*(?:\.\d+)?$/ Validate for a numeric value (1,000.00 or 1000 both are valid). MIXED /^[\w\s-]+$/ Validate an alphanumeric string (no special chars) NAME /^['a-zãàáäâẽèéëêìíïîõòóöôùúüûñç\s-]+$/i Validate a name and allow punctuation. A custom regex will be needed to validate non-roman alphabet names, see xRegExp plugin. NOSPACE /^(?!\s)\S*$/ Validate a spaceless string TRIM /^[^\s].*[^\s]$/ Validate a spaceless string at start or end DATE /^\d{4}-\d{2}-\d{2}(\s\d{2}:\d{2}(:\d{2})?)?$/ Validate a date YYYY-MM-DD EMAIL /^([^@]+?)@(([a-z0-9]-*)*[a-z0-9]+\.)+([a-z0-9]+)$/i Validate an email URL /^(https?:\/\/)?((([a-z0-9]-*)*[a-z0-9]+\.?)*([a-z0-9]+))(\/[\w?=\.-]*)*$/ Validate an url PHONE /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/ Validate a north american phone number OPTIONAL /\S/ With this rule a field becomes optional as long as it is empty. If a value is set inside the field, the validation applies. * COMPARISON /^([LV])([<>]=?|==|!=)([^<>=!]+?)$/ The comparison rule allows to compare the V (value) or L (length) of a field with either a predefined value or an other field using the "name" attribute as a target. <!-- Value must be greater or equal to 18 --> <input name="restriction[age]" data-validation="[V>=18]"> <!-- Password must be between 8 and 32 characters --> <input name="signin[password]" data-validation="[L>=8, L<=32]"> <!-- Email confirmation must match email --> <input name="signup[email]" data-validation="[EMAIL]"> <input name="signup[email-confirm]" data-validation="[V==signup[email]]]">

API

The API allows to reach attributes using jQuery's syntax and format the result to be interpreted by the validation plugin.

Methods Parameters Description .addValidation( validation ) validation {string|array} Adds a validation data attribute "data-validation" to a selected DOM element similar to jQuery's ".addClass()". // As String, separated by a coma for multiple $( "selector" ).addValidation("NOTEMPTY"); $( "selector" ).addValidation("NOTEMPTY, L>=6"); // As Array $( "selector" ).addValidation(["NOTEMPTY", "L>=6"]); .removeValidation( validation ) validation {string|array} Removes a validation data attribute "data-validation" to a selected DOM element similar to jQuery's ".removeClass()". // As String, separated by a coma for multiple $( "selector" ).removeValidation("NUMERIC"); $( "selector" ).removeValidation("NUMERIC, V>=100"); // As Array $( "selector" ).removeValidation(["NUMERIC", "V>=100"]); .addError( error ) Advanced error {object} This API method can only be used after the Validation has been instantiated and with the same jQuery selector to recuperate the validation options. - Demo * For example, using $("#myForm").addError( ... ); would not work since the form validation was initiated with $("form#myForm") jQuery selector. Another important thing to keep in mind is that an error needs an input name reference to be correctly added. $("form#myForm").validate(); // Good $("form#myForm").addError({ "inputName": "errorMessage", "secondInputName": [ "array of messages" "can contain multiple" ] }); // Bad, no inputname is referenced to attach the error $("form#myForm").addError("errorMessage"); .removeError( inputName ) Advanced inputName [optional] {string|array} This API method can only be used after the Validation has been instantiated and with the same jQuery selector to recuperate the validation options. - Demo $("form#myForm").validate(); // Clears all form errors $("form#myForm").removeError(); // Clears only input-specific errors $("form#myForm").removeError([ "inputName", "secondInputName" ]); .validate( 'destroy' ) Advanced destroy {string} Destroys the Validation instance. This API method can only be used after the Validation has been instantiated and with the same jQuery selector to recuperate the validation options. - Demo $("form#myForm").validate(); // Destroy the Validation on specified form $("form#myForm").validate('destroy'); $.alterValidationRules( ruleObject ) Advanced ruleObject {object|array} Alters the global validation rules and messages for every Validation instances. The object requires rule , regex and message keys. If you want to add multiple rules, simply put your objects inside an array. This method has to be called before the Validation gets initiated - Demo $.alterValidationRules({ rule: 'COMPLEX', regex: /^(?=.*\d+)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{6,16}$/, message: '$ must contain one number and one letter (lower and uppercase).' }); $.alterValidationRules({ rule: 'NOTEMPTY', message: 'Changing the not empty global message' });

Debug

* As of 1.3.2, the debug has been removed from jquery.validation.min.js to lighten the file.

If you want to debug your application use the non-compressed version as .min is meant for production environment.

Option Type Description debug {boolean} [optional] false (default) When debug configuration is set to true, information about the form validation will be printed in the browser console (F12). If you have difficulties to get the validation working on one of your form(s) try to activate the debug mode. - Demo * The debug should be removed once the configuration is set properly. $("form#myForm").validate({ debug: true });

Some browser may not display the debug information, make sure you are using the most recent version of Chrome or Firefox.

* The following example of debug console is viewed inside Chrome. - Demo

Flowchart

Initialization

The form validation preparation consists of loading the scripts properly and instantiating the validation object with the correct configuration.

* If the validation gets dropped, a debug message will be thrown inside the console.

Submit Validation

The submit form validation process once the button is trigger .

* At any moment if an unwanted behavior occurs, a message will be outputted through the debug console.

Dynamic Validation