Ads

Monday 8 December 2014

Guardian – All-purpose form validation jQuery plugin

form




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
<link rel="stylesheet" href="css/guardian.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/jquery.guardian-1.0.min.js"></script>

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.
<form id="example1" action="javascript:alert('Validation Successful')">
    <div>
        <label>Name<span class="red">*</span></label>
        <input type="text" name="name" required="required">
    </div>
     
    <div>
        <label>Email<span class="red">*</span></label>
        <input type="email" name="email" required="required">
    </div>
     
    <div>
        <label>Phone</label>
        <input type="tel" name="phone">
    </div>
     
    <input type="submit" name="submit" value="Submit">    
</form>

3. JAVASCRIPT
$('#example1').guardian();

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.
    <textarea name="Custom_1_" rows="2" cols="50" class="comment" id="comment" tabindex="12" maxlength="250" data-counter="true"></textarea>
    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”.
    <input type="text" name="phone" data-empty-message="Please provide your phone number.">

    The following is the HTML structure created for the error message. NOTE: Both error message and empty message share the same element.
    <p class="ui-error-message" id="error-message-phone"></p>
    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”.
    <input type="text" name="phone" data-error-message="Please use a valid phone number">

    The following is the HTML structure created for the error message. NOTE: Both error message and empty message share the same element.
    <p class="ui-error-message" id="error-message-phone"></p>
    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.
    <input type="text" name="phone" data-pattern="phone">
    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
    <input type="text" name="phone" data-pattern="phone" required="required">

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.
$(document).ready(function() {
  $('#contactForm').guardian({
    invalid:'my-invalid-class',
    failure: function() {
      $('#contactForm').prepend('<span>There are '+this.getInvalid().length+ ' invalid fields.</span>');
    }
  });
});

    before

    Function

    If set, invokes before submit validation

    Default: null
    $('form').guardian({
      before:function() {
        console.log(this);
      }
    });
    extend

    Function

    If set, invokes after initialization

    Default: null
    $('form').guardian({
      extend:function() {
        console.log(this);
      }
    });
    failure

    Function

    If set, invokes after submit validation has failed

    Default: null
    $('form').guardian({
      failure:function() {
        console.log(this);
      }
    });
    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
    $('form').guardian({
      success:function() {
        console.log(this);
      }
    });
    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
    $('form').guardian({
      validateCustom:function(el) {
        console.log(el);
      }
    });

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.
    <div data-group-name="name" id="name" data-group-members="FirstName LastName">
    <label for="FirstName">First Name</label><br>
    <input type="text" id="FirstName" name="FirstName" class="text" title="" tabindex="1" value="" data-pattern="num" min="1" max="10" required="" data-error-message="First Name is required.">
    
    <label for="LastName">Last Name</label><br>
    <input type="text" required="" name="LastName" id="LastName" class="text" title="" tabindex="2" value="" data-pattern="alpha" data-error-message="Last Name is required">
    </div>

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.
<fieldset id="areas_of_interest" data-group-name="areas_of_interest" data-group-min="3" data-group-max="5" data-group-members="areas_of_interest">
<input type="checkbox" name="areas_of_interest" id="Annuities" value="Annuities" tabindex="16" class="float-left no-border"><label for="Annuities" class="float-left"> Annuities</label>

<input type="checkbox" name="areas_of_interest" id="Financial_Planning" value="Financial" tabindex="20" class="float-left no-border"><label for="Financial_Planning" class="float-left">Financial Planning</label>

<input type="checkbox" name="areas_of_interest" id="Mutual_Funds" value="Mutual Funds" tabindex="24" class="float-left no-border"><label for="Mutual_Funds" class="float-left">Mutual Funds</label>
</fieldset>

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.
<label for="email">E-mail</label><br>
<input type="email" id="email" name="email" class="text" value="" required="" data-pattern="email" data-error-message="Enter a valid E-mail" tabindex="9">

<label for="email">Confirm E-mail</label><br>
<input type="email" id="confirm-email" name="confirm-email" class="text" value="" required="" data-pattern="match" data-match-input="email" data-error-message="Email addresses do not match" tabindex="9">

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:
    $(document).ready(function() {
      $('form').guardian({
        extend: function() {
          var $this = this;
          $this.$el.off('change blur', ':input', $this.onBlur);
        }
      });
    });
    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:
    $(document).ready(function() {
      $('form').guardian({
        failure: function() {
          this.$el.prepend('<span>There are '+this.getInvalid().length+ ' invalid fields</span>');
        }
      });
    });
    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:
    $(document).ready(function() {
      $('form').guardian({
        extend:function() {
          $(window).bind('beforeunload', function(event) {
            //check for changes and that form has not been submitted
            if(this.$status.changed && !this.$status.submitted) {
              return 'You have unsaved changes.';
            }
          });
        }
      });
    });

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.
$('#contactForm').guardian({ extend: function() { console.log(this); } });

The guardian function also returns the Global Object making it possible to access the methods and variables outside of the validate invocation.
var guardian = $('#contactForm').guardian(); console.log(guardian);

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.
    <div data-group-name="name" id="name" data-group-members="FirstName LastName">
    <label for="FirstName">First Name</label><br>
    <input type="text" id="FirstName" name="FirstName" class="text" title="" tabindex="1" value="" data-pattern="num" min="1" max="10" required="" data-error-message="First Name is required.">
    
    <label for="LastName">Last Name</label><br>
    <input type="text" required="" name="LastName" id="LastName" class="text" title="" tabindex="2" value="" data-pattern="alpha" data-error-message="Last Name is required">
    </div>
    $('form').guardian({
        extend:function() {
            this.addGroup($('#name'));
            //$groups['name'] = {min: 0, max: Infinity, count: 0, members: ['FirstName', 'LastName']}
        }
    });
    addInputTypes(object)

    Returns: False

    Object key is a category name, value is a type or data-pattern to an input type category
    $('form').guardian({
        extend:function() {
            this.addInputTypes({'number':'dollar'}); //adds 'dollar' to $numberInputs
        }
    });
    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.
    $('form').guardian({
      extend:function() {
        this.addPattern({prodNum:/\d{7}/});
        //$patterns['prodNum'] = /\d{7}/;
      }
    });
    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.
    $('form').guardian({
        failure:function() {
            var failures = this.getInvald(); //['FirstName','LastName']
        }
    });
    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
    $('form').guardian({
        before:function() {
            console.log(this);
        }
    });
    extend

    Function

    If set, invokes after initialization

    Default: null
    $('form').guardian({
        extend:function() {
            console.log(this);
        }
    });
    failure

    Function

    If set, invokes after submit validation has failed

    Default: null
    $('form').guardian({
        failure:function() {
            console.log(this);
        }
    });
    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
    $('form').guardian({
        success:function() {
            console.log(this);
        }
    });
    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
    $('form').guardian({
        validateCustom:function(el) {
            console.log(el);
        }
    });

No comments:

Post a Comment