Skip to content

Instantly share code, notes, and snippets.

@hkfoster
Last active May 2, 2017 00:08
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hkfoster/26eb1d3ef08220e8dc56 to your computer and use it in GitHub Desktop.
Save hkfoster/26eb1d3ef08220e8dc56 to your computer and use it in GitHub Desktop.
Native JS HTML5 form validation.
/**
* HTML5 Form Validation 0.0.1
* @author Kyle Foster (@hkfoster)
* @license MIT (http://www.opensource.org/licenses/mit-license.php/)
*/
var formValidation = ( function() {
var init = function() {
// Check for HTML5 form validation support
function hasFormValidation() {
return ( typeof document.createElement( 'input' ).checkValidity == 'function' );
}
// Validation handler function
function validityChecker( e ) {
// Assignment
var validity = e.target.checkValidity();
// Class assignment
if ( !validity && this.value ) {
classie.remove( this, 'valid' );
classie.add( this, 'invalid' );
} else if ( validity && this.value ) {
classie.remove( this, 'invalid' );
classie.add( this, 'valid' );
} else if ( !this.value ) {
classie.remove( this, 'valid' );
classie.remove( this, 'invalid' );
}
}
// HTML5 form validation supported
if ( hasFormValidation() ) {
// Assign variables
var inputs = document.querySelectorAll( 'input' );
// Run input `on blur` validation checks
for ( var inputIndex = 0; inputIndex < inputs.length; inputIndex++ ) {
inputs[ inputIndex ].addEventListener( 'blur', validityChecker, false );
}
}
};
init();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment