Make HTML5 form validation cross-browser and with custom callbacks.
Create an HTML form with the correct attributes to enable the HTML Form validation (type
, pattern
and required
) and then call bfrFormValidation.setup
on the form(s) that need to be validated.
The three callbacks, if specified, will be called when validation is not met or met again.
// normal usage
bfrFormValidation.setup('FORM-SELECTOR', onInvalid, onRevalid, onInvalidAll);
// Browserify usage, with example callbacks
var validation = require('./form-validation');
$(function () {
validation.setup('FORM-SELECTOR', function (field) {
//called on an invalid field
$(field).closest('.Field-container').addClass('Field-container--error');
}, function (field) {
//called on an invalid field that has become valid
$(field).closest('.Field-container').removeClass('Field-container--error');
}, function (fields) {
//called on an array of invalid fields
var $firstInvalid = $(fields).eq(0).closest('.Field-container');
var target = $firstInvalid.offset().top - 30;
var duration = Math.abs($(window).scrollTop() - target)+0.2;
$('html,body').animate({
scrollTop: target
}, duration, function () {//watch out, this is called twice because it's on 'html,body'
fields[0].focus();
});
});
});
This is set to only validate required
fields. Types of validation supported:
type=email
type=tel
pattern
(any regex pattern should work)
The library requires jQuery but, given the size, it can be edited to remove this requirement.