2014-12-08

Download   Demo

Guardian is a all-purpose form validation jQuery plugin. It was designed to be flexible and easy to extend to meet any need.

1. INCLUDE CSS AND JS FILES

2. HTML

A form tag must be included and all inputs must be within the form. In Guardian now the novalidate attribute is added to the form tag during initialization. This attribute prevents the browser’s native validation from activating.

Guardian uses input attributes to determine which inputs to validate and how to validate them, see Input Attributes for more information.

3. JAVASCRIPT

4. INPUT ATTRIBUTES

Each input that needs to be validated may include the following attributes, depending on whether the input is required and how the input value should be validated.

data-counter

Attribute

If a input needs to have a character limit, common for textareas, you may add the data-counter attribute. This will add a counter below the field as shown below.

data-empty-message

Attribute

The message that will appear below the input, when a required field is empty. The error message is shown on “blur” as long as the required field is empty and hidden on “focus”.

The following is the HTML structure created for the error message. NOTE: Both error message and empty message share the same element.

data-error-message

Attribute

The message that will appear below the input, when a field is invalid. NOTE: If the data-empty-message attribute is set and the field is empty and required, then the empty message will display instead of the error message. The error message is shown on “blur” as long as the required field is empty and hidden on “focus”.

The following is the HTML structure created for the error message. NOTE: Both error message and empty message share the same element.

data-group-name

Attribute

The name of the group. Every group name must be unique. For more information, see Grouping.

data-group-members

Attribute

A list input names that are part of the group. Names are separated by a space. For more information, see Grouping.

data-match-input

Attribute

The id of the input that needs to be matched. For more information, see matching.

data-pattern

Attribute

The validation pattern that the input value will be validated against (See Global Object:$patterns below). This attribute should be included on every input required or optional (exceptions: radio buttons, check boxes, select boxes), but each input can only have one pattern. If data-pattern is not included the input will be validated as alphaNum.

required

Attribute

This declares that the input cannot be left blank. If required is set, but the data-pattern attribute is not, the input will be validated as alphaNum

5. OPTIONS

Guardian has made it easy to customize and extend the plugin.

There two types of options, variables and functions. Variables are used to store class names and string data, where as functions allow for the functionality of the plugin to be extended or customize it for your specific needs. For examples on extending the Guardian, see Extending.

before

Function

If set, invokes before submit validation

Default: null

extend

Function

If set, invokes after initialization

Default: null

failure

Function

If set, invokes after submit validation has failed

Default: null

highlight

String

Name of the class for fields that have focus

Default: ‘ui-state-highlight’

invalid

String

Name of the class for invalid fields

Default: ‘ui-state-invalid’

success

Function

If set, invokes after submit validation is successful

Default: null

valid

String

Name of the class for valid fields

Default: ‘ui-state-valid’

validateCustom(jQuery object)

Function

Use to create a custom validation process for inputs within the ‘custom’ catagory (not available for select boxes or textareas)

Default: null

6. GROUPING

Grouping is a means of validating multiple inputs as one. Meaning that all inputs must valid for the group to be valid. Grouping could also be used to set a specific element to receive the state classes. All group data is stored within the Global Object in the $groups object. Groups are adding automatically during initialization.

To use grouping, the data-group-name, the data-group-members and id attributes must be added to a parent tag. The following is example of input grouping

data-group-name

Attribute

The name of the group. Every group name must be unique.

data-group-members

Attribute

A list input names that are part of the group. Names are separated by a space.

id

Attribute

This need to be the same value as data-group-name.

Checkbox grouping is slightly different in respects, the parent has optional data-group-min and data-group-max attributes and checkbox groups will appear in the $inputs object as one group, whereas input grouping show each individual input.

The following is an example of checkbox grouping.

7. MATCHING

Matching is a used to confirm that the value of one inputs matches that of another. This would commonly be used to confirm an email address or password.

data-pattern

Attribute

To used matching, data-pattern must have a value of match.

data-match-input

Attribute

The id of the input that needs to be matched.

The following HTML is an example of how to use matching.

The following is a few commons ways to extend Guardian.

7. EXTENDING

Disable validating on blur

To disable the inputs from validating on blur use the extend option, as shown below:

Display the number of invalid fields on submit

To display a message with the number of invalid fields, use the failure option, as shown below:

Alert user of unsaved changes

To add a confirmation box that alerts the user of unsaved changes before the user leaves the page use the extend option, as shown below:

8. GLOBAL OBJECT

The major difference between version 2 and version 3 is the introduction of the Global Object. All objects, arrays, methods and variables are available through the Global Object.

The Global Object is accessible from any settings function (e.g. extend) through the this variable, as shown below.

The guardian function also returns the Global Object making it possible to access the methods and variables outside of the validate invocation.

9. GLOBAL OBJECT: $pattern

$patterns is an object of regular expressions used the validation of input value. The name of each pattern can be used in the value of the data-pattern attribute. The following is a list of the patterns found in the $patterns object. Additional patterns maybe add using the addPatterns(obj) method.

For security reasons, text inputs and textareas that have no pattern attribute, but are required or have a value are validated using alphaNum.

alpha

RegExp

Description: characters (lower and upper) + “_” + “‘” + “&”

RegExp: /^[a-z_’&]+$/i

alnum

RegExp

Description: characters (lower and upper) + numbers + “_” + “‘” + “&”

RegExp: /^[\w’&]+$/

number

RegExp

Description: numbers (integers and decimals)

RegExp: /^(-?)((\d+)|(\d+).(\d*))$/

zip

RegExp

Description: zip code (5 or 9)

RegExp: /(^\d{5,9}$)|(^\d{5}-\d{4}$)/

currency

RegExp

Description: numbers or decimals (2 places) with optional $

RegExp: /^[$]?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?$/

year

RegExp

Description: full year either 19 or 20 prefix

RegExp: /(^(19|20)\d{2})$/

phone

RegExp

Description: 10 digit phone any standard format, number is reformatted on blur

RegExp: /^\(?(\d{3})\)?[-. ]?(\d{3})[-. ]?(\d{4})$/

email

RegExp

Description: email address allowing ‘.’, ‘-‘, ‘_’ and ‘&’, 2 to 6 character domain

RegExp: /^[\w&]([\w\-\.’&]*)@([\w\-\.]*)(\.[a-z]{2,6}(\.[a-z]{2}){0,2})$/i

url

RegExp

Description: web address formatting

RegExp: /^(([http|https]+):)(\/{2})([0-9.\-A-Za-z]+)\.([0-9.\-A-Za-z]+)\.([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/

date

RegExp

Description: month day year date format allow for full, abbreviated, or number months, one or two digit days, and two or four digit years (four digit year most begin with 19 or 20)

RegExp: /^(Jan|January|Feb|February|Mar|March|Apr|April|May|Jun|June|Jul|July|Aug|August|Sep|September|Oct|October|Nov|November|Dec|December|(0?\d{1})|(10|11|12))(-|\s|\/|\.)(0?[1-9]|(1|2)[0-9]|3(0|1))(-|\s|\/|\.|,\s)(19|20)?\d\d$/i

10. GLOBAL OBJECT: $status

$status is used to monitor the current status of the form based on the user action.

changed

Boolean

Description: equals true if any field value has changed since initialization

submitted

Boolean

Description: equals true if the form has been submitted

11. GLOBAL OBJECT: Other Objects

The following are additional objects within the Global Object.

$el

jQuery Object

Description: jQuery object for the form being validated

$inputs

Object

Description: object of the inputs that have been validated

$groups

Object

Description: object of the groups available within the form, groups are added during initialization, groups can be manually added using addGroup(el)

12. GLOBAL OBJECT: Input Category Arrays

Input Category Arrays are used to categorize inputs based on type or data-pattern. Additional types can be added to any category by using addInputTypes(obj) method.

$checkboxInputs

Array

Description: checkbox inputs

Value: [‘checkbox’]

$customInputs

Array

Description: user generated list of inputs, used in conjuction with validateCustom(el)

Value: []

$emailInputs

Array

Description: inputs with a type or data-pattern of ‘email’

Value: [‘email’]

$fileInputs

Array

Description: inputs with a type of ‘file’

Value: [‘file’]

$hiddenInputs

Array

Description: all inputs with a type of ‘hidden’, hidden inputs are not validated

Value: [‘hidden’]

$matchInputs

Array

Description: inputs with the data-pattern of ‘match’, see matching for more information

Value: [‘match’]

$numberInputs

Array

Description: inputs with a type of ‘number’ or data-pattern of ‘num’, number inputs are validated that are within min and max (default:-Infinity and Infinity)

Value: [‘number’, ‘num’]

$phoneInputs

Array

Description: inputs with a type of ‘tel’ or data-pattern of ‘phone’, phone inputs are validated and reformatted

Value: [‘tel’, ‘phone’]

$radioInputs

Array

Description: radio inputs

Value: [‘radio’]

$textInputs

Array

Description: standard text inputs with a type of ‘text’ or ‘password’

Value: [‘text’,’password’]

13. GLOBAL OBJECT: Methods

The following are methods intended for public use within any setting function (e.g. extend) through the this parameter.

addGroup(jQuery object)

Returns: False

A new group is created based on the group attributes found in the provided jQuery object and added to the $groups object. The jQuery object must have the attributes data-group-name anddata-group-members.

addInputTypes(object)

Returns: False

Object key is a category name, value is a type or data-pattern to an input type category

addPattern(object)

Returns: False

A new pattern is added to the $patterns object. The object should consist of a ‘name':’regexp’ pairing. The object may contain many pairings.

getInvalid()

Returns: Array

Retrieves an array of names of all currently invalid inputs. NOTE: inputs that have not been validated will be neither valid nor invalid.

isFF3()

Returns: Boolean

Checks if the browser is Firefox 3.0 or older

isIE()

Returns: Boolean

Checks if the browser is Internet Explorer

validateAll()

Returns: Boolean

Validates the entire form. Returns true if the no validate errors found.

validateElement(jQuery object)

Returns: False

Validates the provided jQuery object and sets appropriate class (‘ui-state-valid’ or ‘ui-state-invalid’) to the parent.

14. GLOBAL OBJECT: Other Methods

formatPhone(string)

Returns: String

Formats a 10 digit phone number to following pattern: (xxx) xxx-xxxx

onBlur(event)

Returns: false

On blur and on change handler for form inputs.

onFocus(event)

Returns: false

On focus handler for form inputs.

validationHandler(jQuery object)

Returns: false

Called by the guardian functions, handles displaying result. Adds classes to the element parent. Note: if using validateCustom you must call this method or create your own handler.

validateCheckbox(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘checkbox’ category

validateEmail(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘email’ category

validateFile(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘file’ category

validateHidden(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘hidden’ category

validateMatch(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘match’ category

validateNumber(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘number’ category

validatePhone(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘phone’ category

validateRadio(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘radio’ category

validateSelect(jQuery object)

Returns: Boolean

Used by validateElement, for validating select boxes

validateText(jQuery object)

Returns: Boolean

Used by validateElement, for inputs within the ‘text’ category

validateTextarea(jQuery object)

Returns: Boolean

Used by validateElement, for validating textareas

15. GLOBAL OBJECT: Settings

The following are the intended variables to be updated through the guardian invocation.

before

Function

If set, invokes before submit validation

Default: null

extend

Function

If set, invokes after initialization

Default: null

failure

Function

If set, invokes after submit validation has failed

Default: null

highlight

String

Name of the class for fields that have focus

Default: ‘ui-state-highlight’

invalid

String

Name of the class for invalid fields

Default: ‘ui-state-invalid’

success

Function

If set, invokes after submit validation is successful

Default: null

valid

String

Name of the class for valid fields

Default: ‘ui-state-valid’

validateCustom(jQuery object)

Function

Use to create a custom validation process for inputs within the ‘custom’ catagory (not available for select boxes or textareas)

Default: null

Show more