ht5ifv

HTML5 inline form validator

API - documentation

  1. Introduction
  2. Instance Methods
    1. Options
      1. Options for global and local scope
        1. classes
        2. targets
        3. callbacks
        4. events
        5. restrictions
      2. filter
      3. Options for contexts
        1. radio
        2. checkbox
        3. select
        4. textarea
        5. types
      4. Boolean options
    2. Methods
      1. init
      2. validate
      3. valid
      4. reset
      5. reload
      6. clean
      7. destroy
  3. Static Methods
    1. extend
    2. defaults
    3. register
    4. unregister
    5. clean
    6. use
The ht5ifv only expose two methods: The first one is used to extend or replace the ht5ivf with new restrictions. Througth it the developer has access to a set o static methos. The second method is intended to be used by developers who wish to add inline validation to HTML5 forms. This second method provides access to instance methods.

Instance Methods

Usage: $(selector).htivf([method],[options])
Invoked without arguments assumes init method which installs inline validation for all defined HTML5 constraints/restrictions (required, pattern, min, max) as well as implicit restrictions associated with the input types. If no options are provided it uses internal defined defaults. When options are present they will overlap the internal defaults.
In most situations those defaults should be appropriate but the developer may want/need to redefine them or even add or suppress new restrictions. Those operations can be done through the options parameter when installing the ht5ifv (default init method) or through the static method jQuery.htifv(). For this second alternative see the api for that method
Example:
$(document).ready(function(){
   $('form').ht5ifv();
});

Options

The second argument is a map of options in the form key:value which allows the (re)definition of the classes to use in error situations, the targets where those should be displayed, the events that trigger the validation or checking, callbacks and some minor important options. All keys are optional.
Some od these options may have global or local scope. We call it global when it is defined at top level and local when defined in context of other option.
Local scopes always take precedence over global ones
For method init(the default) the options can be grouped in 4 groups. In the first group there are the options which may be used at global or local scope. The second group just contains one special option. The third group defines local contexts where the first group may also be used. The last group is just a set of boolean options
In the following sections those options are described
The following group of options can be used at global scope or in a local scope. The provided examples show how to use it at global scope. When used in the context of other options will have local scope
  • classes
    When the value is a map it associates (sub)states errors with CSS classes
    If the developer wishes to change how the flagged error is displayed it may be changed here, as exemplified:
    $(document).ready(function(){
       $('form').ht5ifv({
        classes:{
    	  valid:'',                            //it suppress any visual effect for valid fields
    	  invalid:'my-error-class',            //use my-error-class to flag the invalid fields
          //If you intend to add new restrictions you may define here how those errors look like
    	  myNewRestriction:'restrictionError' 
        }                
       });
    });
    
    Alternatively a function may be provided. It receives the restriction as a parameter and must return a string with class names that will be used to flag the fields non conforming with the restriction.
    $(document).ready(function(){
       $('form').ht5ifv({
        classes: function($r){ return 'my-class-for-'+$r}              
       });
    });
    
    By defaults this option is assumed to be classes: function($restriction){ return 'ht5ifv-show-' + $restriction}
  • targets
    The targets option defines where the flags should be raised. It may be defined in a compact form or detailed by restriction. In both cases the developer should provide functions which must return a set of jQuery DOM elements
    In the compact form it is a function which receives two parameters. The first one is the jQuery object representing the form field and the second is a string representing the type of error
    $(document).ready(function(){
     $('form').ht5ifv({
       targets:function($field,$type){return $field}              
     });
    });
    
    Alternatively it may be specified restriction by restriction as a map where the keys are the restriction names. In this case the function only receives one parameter, the jQuery object representing the field where the error occurs.
    $(document).ready(function(){
     $('form').ht5ifv({
        targets:{
            required:function($field){return $field},
            type:function($field){return $field.parent()},
            min:function($field){return $field},
            max:function($field){return $field},
            pattern:function($field){return $field},
            valid:function($field){return $field.parent()},
            invalid:function($field){return $field.parent()}        
        };
     });
    });
    
    The default is targets:function($field,$restriction){return $field}
  • callbacks
    This option allows us to define callback functions which may be invoked every time a validate or check is performed or when a (sub)state transition occurs.
    Like targets it may be defined as an unique, two parameters, function or a map of restrictions and one parameter functions
    $(document).ready(function(){
     $('form').ht5ifv({
       callbacks:{
        valid: function($field){alert('The field is now valid.Thank you')},              
        invalid: function($field){alert('The field is invalid.Please fixe it')},              
        pattern: function($field){alert('The field does not very the pattern')},
        type: function($field){     //implicit restriction associated to the type in input elements 
            alert('The value in the field ' + $field.attr('name') 
            + ' is invalid for the type ' + $field.attr('type'))
        }
       }     
     });
    });
    
    By default it is a null function:callbacks:function($field,$restriction){}
    The definitions in this option have a global scope
  • events
    The events option defines when the validate (test restrictions) or check (compute valid or invalid state) will be performed.
    This option is a map of only two keys, validate and check. The values must be a list of events in a space separated string. Each event should be defined in ht5ifv namespace. This is not strictly required but if omitted the ht5ifv won't unbind them when it is destroyed
    $(document).ready(function(){
     $('form').ht5ifv({
        events:{  
            validate: 'mouseover.ht5ifv focus.ht5ifv', 
            check: 'blur.ht5ifv mouseout.ht5ifv',
        }     
     });
    });
    
    The values by default are:
    events:{  
      validate: 'focus.ht5ifv keyup.ht5ifv', //validate every time a key is released or get the focus
      check: 'blur.ht5ifv'                   //only check status on blur 
    } 
    
    Note: By default this won't be applied to the fields select, radio and checkbox, as these fields have, also by default, local definitions. It means that if the developer needs to change the events for those fields she must define them in the correspondent local scope, not at global scope
  • restrictions
    In a first form it (re)defines handlers to validate the field against a named restriction. It is a map where the keys are the restriction names and the values are functions which must return a boolean value.
    Those handlers receive two parameters, the first to identify the form field and the second is a boolean to flag if the empty fields should be ignored or not
    $(document).ready(function(){
     $('form').ht5ifv({
        restrictions:{  
            required: function($field){ //redefine the HTML5 required constraint/restriction
                var $v = $field.val();
                return $v && /^[^\s]*$/.test($v) //returns true if not empty and haven't white spaces
            }, 
            data-size: function($field,$ignoreEmpty){ 
              //New restriction, ex: < input type="text" data-size="9" name="tel"/ >
              var $v = $node.val();
              var $l = $v.length;
              var $m = $v.data('size');    
              return ($v =='' && $ignoreEmpty ) || $l == $m        
            }
        }     
     });
    });
    
    By default only two restrictions are defined globally, the required and the pattern. All others restrictions (type, min, max) are locally defined. Besides, the fields radio and checkbox also redefines the restriction required. That means, if the developer wants to redefine them, she must do it locally
    In order to simplify the definitions of new restrictions an alternative format is possible. Instead of associating the restriction name with a handler the developer may associate it with a map with following keys:
    • handler: Specify the handler to be invoked to determine if the restriction is satisfied or not
    • classe: The CSS classes to be applied when in error. The key is 'classe' with 'e' in the end to avoid the javascript reserved word 'class'
    • target: Where the error should be flagged
    • callback: A callback function to be invoked when a (sub)state transition occur
    $(document).ready(function(){
        restrictions:{
            data-size:{
                handler: function($field,$ignoreEmpty){ 
                  var $v = $node.val();
                  var $l = $v.length;
                  var $m = $v.data('size');    
                  return ($v =='' && $ignoreEmpty ) || $l == $m        
                }
                classe: 'my-class-for-size',
                target: function($field){return $('#errorMsg')}
                callback: function($field){
                    $('#errorMsg').html('The value in the fiel ' + 
                        $field.attr('name') + ' should be ' + 
                        $field.data('size') + 
                        ' caracters in length');
                }
            }
        }
    })
    
The following option can only be used at global scope
  • filter
    This option gives more control over the fields on which the validation process occurs
    It receives, as a parameter, a set of all inputs, selects and textareas fields present in the form (or other selector) except inputs of type button, reset, submit and images. In the end it should return a set of inputs, selects or textareas. It could be a subset, the same set, or even a completely new set of elements of the received one.
    $(document).ready(function(){
        filter:function($fields){return $fields.not('[readonly]');}
    },      
    The filter by default is function($inputs){return $inputs.not('[type="hidden"]');}
The following options defines local scopes where the first set, of above options, may also be used. The local scopes always take precedence over global scopes
  • radio
    This element defines a local scope for definitions for inputs of type radio
    $(document).ready(function(){
     $('form').ht5ifv({
       radio:{  //the target option bellow will be used only by inputs of type radio
        targets: function($field,$r){return $field.parent()}
       }
     });
    });
    
    Notice that by default errors are flagged on the field itself. However for radios and checkboxes this doesn't produce any visual effects on browsers.
    We faced the temptation of defining the parent as the target for these two kinds of inputs but that could produce undesirable effects in situations where those inputs are not aggregated in an exclusive wrap element
    As so we left it to the developer to decide where she wants to see the errors. By default they won't be visually flagged. A code as the above example could be enough
    By default this option assumes the following values:
    radio:{
        restrictions:{
            required:function ($radioGroup,$node){
                return $radioGroup.filter(':checked').length  0
            }
        },
        events:{
            validate: 'change.ht5ifv',
            check: 'change.ht5ifv'
        }
    }
    
    Also notice that for radio inputs the validation invokes the handler not with the field itself as first parameter but with a set of all inputs of type radio sharing the same name within the same form.
  • checkbox
    Similar to radio but for ckeckboxes
    By default this option assumes the following values:
    checkbox:{
        restrictions:{
            required: function($node){
                return $node.is(':checked')
            }
        },
        events:{
            validate: 'change.ht5ifv',
            check: 'change.ht5ifv'
        }		
    }
    
  • select
    Similar to radio but for selects
    By default this option assumes the following values:
    select:{
        restrictions:{
            required:function ($node){
                return $node.val() != null;
            }
        },
        events:{
            validate: 'change.ht5ifv',
            check: 'change.ht5ifv'
        }
    }
    
  • textarea
    This element defines a local scope for definitions for textarea form elements
    By default this element is empty
  • types
    Defines local scopes for each input type. It is a map of following input types:
    • color
    • date
    • datetime
    • datetime-local
    • email
    • month
    • number
    • password
    • range
    • search
    • tel
    • text
    • time
    • url
    • week
    Additional the type _defaults is also used to define a local scope for unknown types.
    For each type above the implicit restriction is defined by default according to the W3C specifications. The restrictions min and max are defined to these types: date, datetime, datetime-local, month, number, range, time and week
    If the developer needs to add a new type it should be defined here
    Some examples
    • Add restricton min-length to password fields
      $(document).ready(function(){
       $('form').ht5ifv({
         types:{
          password:{
            restrictions:{
              'data-min-length':function($node,$ignoreEmpty){
                var $v = $node.val();
                var $l = $v.length;
                var $m = $v.data('minLength');    //see jquery 1.6 .data() method
                return ($v =='' && $ignoreEmpty ) || $l = $m        
              },
            }
          }
         }
       });
      });
      
    • Define the type city
      $(document).ready(function(){
       $('form').ht5ifv({
         types:{
          city:{
              restrictions:{
                  type:function($node,$ignoreEmpty){
                      var $v = $node.val();
                      return ($v =='' && $ignoreEmpty ) || /^[a-z\-\s'.]+$/.test($v)       
                  }
              }
          }
         }
       });
      });
      
    • Change date format to be mm/dd/yyyy (Simplified! See the function checkDateFormat in ht5ifv code )
      $(document).ready(function(){
       $('form').ht5ifv({
         types:{
          date:{
            restrictions:{
              type:function($node,$ignoreEmpty){
                return $node.val().match(/^(\d{2})\/(\d{2})\/(\d{4})$/)
              }
            }
          }
         }
       });
      });
      
This group of options defines only booleans
    callbackOnlyStatusTransitions: true, callbackOnlyErrorTransitions: true, ignoreEmptyFields: true, safeValidate: true, checkDisable:true
  • browserValidate
    By default the ht5ifv turns off browser validation. Set this value to true if you want to use the browser internal validation cumulatively
  • callbackOnlyStatusTransitions
    The callback function for (in)valid state is only invoked when a state transition occurs. Set this option to false if you need to receive a callback every time a check action is performed
  • callbackOnlyErrorTransitions
    The callback function for any restriction is only invoked when, as result of a validation, the field enters into the correspondent error sub-state. Set this option to false if you need to receive a callback every time a validation is performed and the field enters or stays in error.
  • ignoreEmptyFields
    By default empty fields are not validated, except for the required restriction. Set this option to false if you don't want to ignore it
  • safeValidate
    A check action computes the state (valid or invalid) of a field as the result of a validation action for each restriction. A field is invalid if at least one validation evaluates to false.
    Normally a validation action must have a higher frequency of running than a check action. For example, a validation may occur every time a key is pressed and the check only occurs when the field loses the focus. However, as this is configurable it may happen that a check is performed without a previous validate action. This can leave the field in an incorrect situation where it is invalid and is not flagged as so.
    For that reason, by default, a check action triggers a validation event before computing the field state.
    This behaviour could be disabled by setting this option to false. It will be safe to do that if it is ensured that a validate event occurs always before a check event.
  • checkDisable
    By default the disabled fields are not flagged. Set this option to false to also validate and check disabled fields
  • validateOnSubmit
    Set this option to false if you don't want to perform validation on submit.
    Setting validateOnSubmit: false and browserValidate: true allows using ht5ifv to perform inline validation and the builtin browser validation to perform validation on submit

Methods

  • init
    This is the default method and when invoked it overrides the defaults with values in the options and binds restriction handlers for each form field. See options
    This method is chainable
  • validate
    Triggers validate and check actions for each form field.
    This method is chainable.
  • valid
    The same as validate but returns a boolean.
    It returns true if all the fields are valid.
  • reset
    Resets the form
    This method is chainable.
  • reload
    Reloads the fields with default values. If some fields are filtered out (option filter) they won't be reloaded. For the user, this is the only noticeable difference to the reset method. Internally the reset method triggers a reset event while the default method finds the default values for each field and sets it
    This method is chainable.
  • clean
    Clean the fields
    This method is chainable.
  • destroy
    Unbind all previous .ht5ifv binds
    This method is chainable.
  • Example:
    $(document).ready(function(){
        var $options = { /*options*/  };
        $('#fexample1').ht5ifv($options).ht5ifv('validate'); //init the ht5ifv and then validate
        $('#_validate').click(function(){
                $('#fexample1').ht5ifv('validate'); //Validate all fields and flag them if they are in error
        });
        $('#_reset').click(function(){
            $('#fexample1').ht5ifv('reset');	//Reset the form. It trigger the jQuery reset event
        });
        $('#_reload').click(function(){
            $('#fexample1').ht5ifv('reload');	//Reload the default values 
        });
        $('#_clean').click(function(){
            $('#fexample1').ht5ifv('clean');	//Clean all fields  
        });
        $('#_destroy').click(function(){
            $('#fexample1').ht5ifv('destroy');	//destroy any ht5ifv data or bind  
        });
        $('#_init').click(function(){
            $('#fexample1').ht5ifv('init',$options);	//Init the ht5ifv  
        });
        $('#_valid').click(function(){
            alert($('#fexample1').ht5ifv('valid'));  //Similiar to validate but returns a boolean
        });
    })                        
    

Static Methods

Usage: $.htivf(method,[args])

These set of method allows to extend the ht5ify for supporting new restrictions or new input types. It may also be used to redefines the exiting ones.

Method extend

Usage: $.htivf('extend',options,[global],[selfContained])
This method allows to extend the default options with the options passed in second argument The options are the same as described for the method .htivf('init',$options). However, unlike that method the options classes, targets, callbacks, events and restrictions when defined at top level only have global scope for the restrictions defined in this method. That is, the top level defined options still have global scope but they just apply to the module. This is done to avoid conflicts with others extensions.
Example:
/********************PT formats extension module************************/
/* It defines some formats used in Portugal */
$.ht5ifv('extend',{
  types:{
    ptcp:{ //PT Car number Plates
      restrictions:{
        type: function($node,$ignoreEmpty){ // AA-00-00 or 00-AA-00 or 00-00-AA 
          var $v = $node.val();
          var $re = /^[A-Z]{2}-[0-9]{2}-[0-9]{2}|[0-9]{2}-[A-Z]{2}-[0-9]{2}|[0-9]{2}-[0-9]{2}-[A-Z]{2}$/;
          return ($v =='' && $ignoreEmpty ) || $re.test($v)         }
      }
    },
    ptpc:{ //PT Postal Code
      restrictions:{
        type: function($node,$ignoreEmpty){ // 0000-000 
          var $v = $node.val();
          return ($v =='' && $ignoreEmpty ) || /^([0-9]{4}-[0-9]{3})$/.test($v)   
        }
      }
    }
  },    
  classes:{
    type: 'ext-error-type' //this class is only applied to types defined here
  }
});                    
If the developer needs to redefine some default options with this method, she should explicit indicate it, by passing the value true on third parameter
For example if a developer has several html forms where she would like to use they own classes she may redefine them once and use it later several times.
$.ht5ifv('extend',{        
    classes: function($restriction){return 'my-class-'+$restriction;}
}, true); //With third parameter true it overlap the global defaults

Method defaults

Usage: $.htivf('defaults')
Expose all defaults and allow the developer to use or change those internal structures
Example:
/*Define a new type but with the same behaviour of an existing one*/
var $d = $.ht5ifv('defaults');
$.ht5ifv('extend',{
	types:{ //myDate is a copy of internal date type
		myDate: $.extend(true,{},$d.types.date)
	}
});                    
Another Example:
/*Change the default classes*/
var $d = $.ht5ifv('defaults');
$d.classes = function($restriction){ return 'My-class-for-' + $restriction};                    

Method register

Usage: $.htivf('register',name,handler[,force])
Register a module which may be used later to install parametrized extensions. The handler is installed under the name name. If the name already exist and force parameter is true it will override the old one.
The handler may receive any number of parameters and should always return a map of options as described in the init instance method. That return map will be used as the second parameter of extend static method
Example (see also use method):
$.ht5ifv('register','cc',function($mode,$name){ //install module cc
	/*Handler usage:
		Example 1 
			JS -> $.ht5ifv('use',['cc','type','CreditCardType']) //use cc module as CreditCardType type   
			HTML -> <input type="CreditCardType"/>		
		Example 2 
			JS -> $.ht5ifv('use',['cc','restriction','CC']) //use cc module as CC restriction    
			HTML -> <input type="text" data-CC="1"/>
	*/
	/* Checksum function */	
	var $creditCard:  function($v){ //Lunh Algorithm
		var $sum = 0;
		for(var $i = $v.length - 2; $i >= 0 ; $i -= 2){
			var $n = 2 * $v.charAt($i);
			if ($n > 9) $sum += $n - 9
			else $sum += $n;
		} 
		for(var $i = $v.length - 1; $i >= 0 ; $i -= 2){
			$sum += 1 * $v.charAt($i);
		}
		return $sum % 10 == 0
	}
	var $options = {}; 
	if (!$name || typeof $name == 'string' && $name.length == 0){
		console.warn('ht5ifv.%S - No name provided for the type/restriction',$name);
	}else{
		if (!$mode || $mode === 'type'){ //by default or when mode is type
			$options.types = (function($o){ //define a type implicit restriction
				$o[$name] = {restrictions:{type: $creditCard}};
				return $o;
			})({});
		}else if($mode === 'restriction'){
			$options.restrictions = (function($o){ //define a global explicit restriction
				$o['data-' + $name] = $creditCard;
				return $o;
			})({});
		};
	}
	return $options; //The register handler must always return a map, even if it is empty
})                    

Method unregister

Usage: $.htivf('unregister')
Unregister a previous registered module

Method clean

Usage: $.htivf('clean')
Remove all registered modules

Method use

Usage: $.htivf('use'[,args])
Evaluates the registered modules handlers and then use the results to install new extensions. If the args are missing all registered modules will be evaluated with defaults values and installed as new extensions.
If the args are present and they are a list of names, the registered handlers with those names will be evaluated with defaults values and installed as extensions.
/*Evaluate creditCard, IBAN and VAT registered handlers and use the results to install new extensions */					
$.ht5ifv('use','creditCard','IBAN','VAT');
Is the args are present and they are a list of arrays the htifv use the first element of each arrays to identify the handler and evaluate it using the values in following positions as arguments for the handler. The args could also be a mixed list of names and arrays
Example (see also register method):
/*Evaluate creditCard handler with parameters 'type' and 'CC' and use the result to install a new restriction*/					
/*Evaluate IBAN with default values and use the result to install a new restriction*/					
/*Evaluate VAT handler with parameters 'restriction' and 'vat' and use the result to install a new restriction*/					
$.ht5ifv('use',['creditCard','type','CC'],'IBAN',['VAT','restriction','vat']);