Last active
May 2, 2017 00:08
-
-
Save hkfoster/26eb1d3ef08220e8dc56 to your computer and use it in GitHub Desktop.
Native JS HTML5 form validation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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