Form Validation
Hubble's FormValidator
provides a powerful module to validate and interact with your forms an easily and quickly.
Validations
Before we look at using the FormValidator
, let's take a look at using the data-attribute
on inputs to tell the module what it should validate.
The data-js-required
specifies a value is required.
The data-js-min-length
specifies the value must be >=
a length in characters.
The data-js-min-length
specifies the value must be <=
a length in characters.
The data-js-validation
specifies a validation pattern preset.
The available presets are:
email
name
creditcard
password
url
list
alpha
numeric
alpha-numeric
Usage
To access the form validator use FormValidator
key via the Module loader.
You must pass a valid form DOM node to the constructor.
Use the isValid
method to check if a form is valid.
Use the showInvalid
method to highlight any invalid inputs.
Use the clearInvalid
method to remove any invalid inputs as well as the form result.
Use the form
method returns an object with all the key/values from the form.
The append
method appends a key/pair to the form object from the form and returns it.
The showResult
method displays the form result.
Example
Below is an example form using the validator. Check the console log for more details.
var Helper = Hubble.require('JSHelper');
var formValidator = Hubble.require('FormValidator', Helper.$('.js-form'));
var submitBtn = Helper.$('button[type=submit]', Helper.$('.js-form'));
var fakeAjax;
submitBtn.addEventListener('click', formHandler);
// Click event handler
function formHandler(e) {
// Stop the form from submitting
e = e || window.event;
e.preventDefault();
// Don't submit if the form if it is being submitted
if (Helper.hasClass(submitBtn, 'active')) return;
// Clear all invalid input classes and form results
formValidator.clearInvalid();
// Clear the timeout
clearTimeout(fakeAjax);
// Validation
if (formValidator.isValid()) {
Helper.addClass(submitBtn, 'active');
fakeAjax = setTimeout(function(){
formValidator.showResult('success');
Helper.removeClass(submitBtn, 'active');
}, 3000);
}
else {
formValidator.showInvalid();
console.log('The form is NOT valid');
}
}