Form Validation Toolkit

Validation Tool's Public Methods

The Validation Toolkit mostly works in the background. There are a few methods that can be called manually.

The validation tool is a jQuery plug-in object '$.validator'. Most function calls are part of this object. Some function calls are part of the jQuery DOM Element object.

jQuery DOM Element Methods

Following are all the different jQuery DOM Element methods related to the validation toolkit:
Method Parameters Description
$('form_selecotr').initValidation()
$('field_selector').initValidation()
options Optional. An options object

Attach (Initiate) the Validation

This method attaches the validation process to a set of elements or the form. It's recommended to attach the validation process to the form so fields are auto validated on change as well as on form submission.

Attach the validation process to a set of fields only if there is a need for validating the fields outside of the form submission.

Here are the options keys:
options.delay: Optional, Boolean. Default is false. Whether to try to initiate with a delay. Works with the 'delay_parent' property.

options.delay_parent: Optional (Required if delay is true), CSS Selector. The CSS selector for the parent container (of the field(s) or the form) - to check when the parent becomes visible

options.toggle_buttons: Optional, Boolean. Default is false. Whether to disable/enable submit buttons. Only works if validation is attached to the form.
options.buttons_css: Optional (Required if toggle_buttons is true), CSS Selector. Default is false. Selector for the buttons to be enabled/disabled on validation.

On FORM validation, two variables are stored in the form's jQuery data:
$('form').data('valStatus'): Boolean. It tells whether all items in the form passed validation or not.
$('form').data('valResult'): Array. The validation result array with a result object for each field, with these keys:
el: The element (jQuery) that was validated
passed: Result of validation - true or false
error: An array with the error code and error description


On FIELD validation, two variables are stored in the element's jQuery data (in addition to attempting to store the parent form's validation result mentioned above):
$(element).data('valStatus'): Boolean. It tells whether all items in the form passed validation or not.
$(element).data('valResult'): Object. The validation result object for the the field, with these keys:
el: The element (jQuery) that was validated
passed: Result of validation - true or false
error: An array with the error code and error description
$('form_selector').uninitValidation()
$('field_selector').initValidation()

Detach (Uninitiate) the Validation

This method detaches the validation process from a set of elements or the form so it stops checking for REQUIRED fields. This is useful to stop REQUIRED validation of certain set of elements if they need to be skipped for any reason.

The fields or the form can be re-attached (initiated) to the validation process by calling the $(selector).initValidation() method.
$('field_selector').attachCustomError() msg Optional, String. The error message to be displayed

Raise and Attach Custom Error

This method is applied to a field for attaching custom errors. Once called, the field is marked for failed validation and the custom message is attached for info bubble display.

Once a custom error is attached, the field will stay as with an error status until the custom error is cleared with the $(field_selector).attachCustomError() call. The parent form will fail validation while the custom error is attached.
$('field_selector').detachCustomError()

Clear and Detach Custom Error

This method is applied to a field for clearing and detaching custom errors. Once called, the field is cleared from the custom eror and marked as validation passed, given that no other validation error is there.

Once a custom error is detached, the parent form is checked for validation status.
$('form_selector').send(); options - Required options object

AJAX Submit a Form

This method will submit a form using AJAX and request JSON data. The form will be submitted to the URL specified in the form's 'action' property using GET or POST as specified in the form's 'method' property. Default is 'POST'.

The options object:

AJAX Attributes
The following are optional AJAX attributes, only supply to override or add to the form values or if submitting a non-form based AJAX request.

options.url: String. Optional. Server path (file) to submit the AJAX request to.
options.method: String. Optional. Values are 'post' or 'get'. Default is the form's method attribute or 'post'.
options.data: String. Optional. The data supplied in URL format i.e. 'name=Miah+Morshed&title=Sr.+Partner'. If added for a form, it will be appended to the form's data.

Functions to Execute
The following are functions that gets executed at various points (times) during the AJAX data submission. Except the for the first one (options.fnBeforeSend), all others get an Object variable data passed to the function. The data object is the AJAX returned JSON data. It is recommended to include at least two keys - data.success (true or false) and data.msg - a message into the AJAX JSON Object so the options.fnSuccess and options.fnFailure functions can be executed according to the result.

In addition to passing the JASON data object to the functions, the jQuery target object (for which the send() command was called), is passed to these functions as a binding so it can be accessed using 'this'.

options.fnBeforeSend: Function. Optional. A function that executes right before the AJAX request is sent.
options.fnBefore: Function. Optional. A function that executes after data is received but before the data is processed. The data object is passed to this function.
options.fnSuccess: Function. Optional. A function that executes if the data.success is true. The data object is passed to this function.
options.fnFailure: Function. Optional. A function that executes if the data.success is false. The data object is passed to this function.
options.fnAfter: Function. Optional. A function that executed at the end after the AJAX data is processed. The data object is passed to this function.

jQuery Validator Object's Methods

Following are all the different atributes and their possible values:
Method Parameters Description
$.validator.validateType() options Required. An options object

Validate Data Type

This method validates data types and returns true or false.

Here are the options keys:
options.value: Required. The value to be tested

options.type: Required, String. The data-type to be tested - 'email' | 'url' | 'number' | 'alphanumeric' | 'phone' | 'date' | 'time'

options.format: Optional. The formats for the data-type to be tested. Not all data-types have formats. Following is a detailed list.
options.type (number) - 'num' | 'int' | 'float' | 'neg' | 'neg-int' | 'neg-float' | 'pos' | 'pos-int' | 'pos-float'
options.type (alphanumeric) - 'username' | 'password'
options.type (phone) - 'international' | 'us' | 'both'
options.type (date) - 'mm/dd/yy' | 'mm/dd/yyyy' | 'm/d/yy' | 'm/d/yyyy' | 'M dd, yyyy' | 'M dd, yy' | 'M d, yyyy' | 'M d, yy' | 'MM dd, yyyy' | 'MM dd, yy' | 'MM d, yyyy' | 'MM d, yy'
options.type (time) - 'hh:mm:ss a' | 'hh:mm:ss' | 'hh:ss a' | 'hh:ss' | 'h:m:s a' | 'h:m:s' | 'h:s a' | 'h:s' | 'HH:mm:ss' | 'H:m:s' | 'HH:mm' | 'H:m'
<input type="text" name="date1" data-val-required="1" value=""  />

//option 1 
var result = $.validator.validateType({
	value: $('input[name=date1]').val(),
	type: 'date',
	format: 'mm/dd/yy'
});

//option 2 - do not supply data format so it uses the defaults
var result = $.validator.validateType({
	value: $('input[name=date1]').val(),
	type: 'date'
});
Method Parameters Description
$.validator.validateField() element Required. The input element to be validated
checkFormStatus Optional, Boolean. Whether to check validation status of all fields for the form and store it at the form level results variable.

Validate an Input Field

This method will validate a single input field based on its validation attribues and will return a validation result object.

If the parent form is already attached to the validator, this method will be automatically fired. The only reason this method should be manually called is if the parent form was not attached to the validator so the inputs need to be validated manually.

The validation result object has the following keys:
el: The element (jQuery) that was validated
passed: Result of validation - true or false
error: An array with the error code and error description
<form name="example">
	<input type="text" name="name" data-val-required="1" value=""  />
	<input type="text" name="email" data-val-required="1" data-val-checkType="email" value=""  />
	<input type="password" name="password" data-val-required="1" data-val-checkType="password" value=""  />
</form>

//Do not attach the validator to the form, so we can use this method
$("input[data-val-checkType], input[data-val-required]").initValidation();

//now manually check validation
$('form[name=example]').submit(function(event){
	
	//store result here
	var result = [];
	
	$(this).find("input[data-val-checkType], input[data-val-required]").each(function(input){
		result[result.length] = $.validator.validateField(input, false);
	});
	
	//Now use the result array to continue form processing
	//Each 'result' item in the array will be an object with the 
	//	following keys - { el: element, passed: Boolean, error: Array }
});

$.validator.validateForm() simulateSubmission Optional, Boolean. Whether to simulate form submission

get Validation Results for a Form

This method check and store the validation result for a form. The form must be passed into the method as its parent object so the form can be referred to as 'this'.

If simulateSubmission is set to false or skipped, the method will simply check and store validation status of all fields for the form.
If simulateSubmission is set to true, it will also simulate a form submission action marking fields that did not pass validation.

The method stores two variables in the form's jQuery data:
$('form').data('valStatus'): Boolean. It tells whether all items in the form passed validation or not.
$('form').data('valResult'): Array. It stores the validation result for each field with validation attributes. Each array item has a result object with these keys:
el: The element (jQuery) that was validated
passed: Result of validation - true or false
error: An array with the error code and error description
If the form is already attached to the validator, this method will be automatically fired. The only reason this method should be manually called is if the form was not attached to the validator so the form needs to be validated manually.

<form name="example">
	<input type="text" name="name" data-val-required="1" value=""  />
	<input type="text" name="email" data-val-required="1" data-val-checkType="email" value=""  />
	<input type="password" name="password" data-val-required="1" data-val-checkType="password" value=""  />
</form>

//Do not attach the validator to the form, so we can use this method
$("input[data-val-checkType], input[data-val-required]").initValidation();

//now manually check validation
$('form[name=example]').submit(function(event){
	
	$.validator.validateForm.attempt(true, this);
	//Function.attemp(arguments, bind) was used to pass the form object to the method
	
	var valResult = frm.data('valResult');
	var valStatus = frm.data('valStatus');
				
	//Now use the valResult array to continue form processing
	//Each 'valResult' item in the array will be an object 
	//	with the following keys - { el: element, passed: Boolean, error: Array }
});



Form and Control Element Events

Following are all the different atributes and their possible values:
Event Description
FORM: 'valSubmit' This event is similar to the native 'submit' event - can be used as an alternative to 'submit'.

This is fired after -
1) a form is submitted and then
2) the validation for the form is completed.

This will allow handling form submissions (instead of using the 'submit' event) while all validation data is available to the event code.
$('form_selector').bind('valSubmit', function(event){
	//Your code for processing form submission
	//$(this).data('valResult') will return an array
	//$(this).data('valStatus') will return true or false
	
});

Event Description
FORM: 'valStatusChanged' This is fired after -
1) each time the form's validation status is checked-rechecked
2) based on the above logic, also fired during form submission

$('form_selector').bind('valStatusChanged', function(event){
	//Your code for taking actions based on form's validation status
	//$(this).data('valResult') will return an array
	//$(this).data('valStatus') will return true or false
	
});
Control: 'valStatusChanged' This is fired when the validation status for a specific form control is checked or rechecked. The validation result is available.

$('form_control_selector').bind('valStatusChanged', function(event){
	//Your code for taking actions based on this element's validation status
	//$(this).data('valResult') will return an object {'passed': Boolean, 'error': String}
	//$(this).data('valStatus') will return true or false
	
});
Control: 'valInitiated' This is fired when the validation scheme is attached to this form item.

This is fired at the end of processing the DOM.initValidation() method.

$('form_control_selector').bind('valInitiated', function(event){
	//Your code here
	
	
});
Control: 'valUninitiated' This is fired when the validation scheme is attached to this form item.

This is fired at the end of processing the DOM.uninitValidation() method.

$('form_control_selector').bind('valUninitiated', function(event){
	//Your code here
	
	
});
Control: 'valReset' This is fired when the validation flag(s) is reset for this form item. The validation results are also reset, if they were set earlier.

This is fired at the end of processing the DOM.resetValidation() method.

$('form_control_selector').bind('valReset', function(event){
	//Your code here
	
	
});