- Overview
- Documents
The jQuery form validation plugin unifies the way to validate HTML forms using JavaScript. It is a simple client-side library that will save you a lot of time when it comes to adding validation on your HTML form inputs or selects!
- Open Source project hosted on Github
- No more duplicated validation code in your project(s)
- The most advanced JavaScript Form Validation plugin HTML5
- Cross-browser client-side form validation solution with documentation and demos available
- dynamic validation available (keypress)
- Supports error message translation
- Deep Customization and flexibility (multiple options and callbacks)
- More, More, More!
sex shop sex shop sex shop sex shop sex shop seks shop spanish fly psikolog sohbet numara sohbet hatti
Source: runningcoder.org
1. INCLUDE JS FILES
<!-- 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
2. HTML
<form id="form-signin_v1" name="form-signin_v1" method="POST"> <label> Username <input name="signin_v1[username]" type="text" data-validation="[NOTEMPTY]"> </label> <label> Password <input name="signin_v1[password]" type="password" data-validation="[NOTEMPTY]"> </label> <input type="submit" class="ui blue submit button" value="Login"> </form>
3. JAVASCRIPT
$('#form-signin_v1').validate();
4. 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: "input[type='submit']", errorClass: "error", errorListClass: "error-list", 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> |
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(). 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 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"> |
5. 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' } } });
$('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); } } } });
$('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: DOM of the form element, you can wrap it with a jQuery selector to find elements Ex: $(node)
- errors: Array of errors only returned by onError callback
Callback | Description |
---|---|
onInit |
Will be executed on Validation initialization. |
onValidate |
Will be executed after the submit.settings.button is triggered and before the Validation. |
onError |
Will be executed if errors are found. * The object of errors will be return as the last function parameter as an "extra" parameter. |
onBeforeSubmit |
Will be executed if no errors are found and before the form gets submitted. |
onSubmit |
Will be executed if no errors are found. * Careful, using this callback will override the native HTML form.submit(). |
onAfterSubmit |
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: DOM of the form element, you can wrap it with a jQuery selector to find elements Ex: $(node)
- input: 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
- errors: Array of errors only returned by onError callback
Callback | Description |
---|---|
onError |
Will be executed if error(s) are found on the dynamic input. |
onSuccess |
Will be executed if no error(s) are found on the dynamic input. |
onComplete |
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.
6. HTML ATTRIBUTES
Attribute | Value | Description |
---|---|---|
data-validation |
{array} |
Contains a list of validation rules. See below for the complete list. If the field contains nodata-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="/^\d|admin|\d$/i" data-validation-regex-message="Word 'admin' is not allowed in $ ..."> |
data-validation-label |
{string}[optional] |
Setting this attribute will override the inputName inside the error message. <!-- Replaces the inputName inside the error message --> <input name="signup[username]" data-validation="[L>=6, L<=24]" data-validation-label="Custom label name"> |
7. VALIDATION RULES
These rules are used inside data-validation attribute formatted as an array.
Rules | Regex | Description |
---|---|---|
NOTEMPTY |
/./ |
Field must not be empty. <!-- Search field must not be submitted empty --> <input name="search[text]" data-validation="[NOTEMPTY]"> |
NUMERIC |
/^[0-9]+$/ |
Validate for a numeric only value. |
MIXED |
/^[\w\s-]+$/ |
Validate an alphanumeric string (no special chars) |
NOSPACE |
/^[^\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 |
|
/^([^@]+?)@(([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 |
/^.*$/ |
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]]]"> |
8. 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 ) |
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. * In this example, using $("#myForm").addError( ... ); would not work since it is not the same jQuery selector. $("form#myForm").validate(); $("form#myForm").addError({ "inputName": "errorMessage", "secondInputName": [ "array of messages" "can contain multiple" ] }); |
*.removeError( inputName ) |
[inputName] 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. $("form#myForm").validate(); // Clears all form errors $("form#myForm").removeError(); // Clears only input-specific errors $("form#myForm").removeError([ "inputName", "secondInputName" ]); |
9. 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. * 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.
10. FLOW CHART
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
The dynamic form validation occurs when an input is trigger.