Skip to content

Instantly share code, notes, and snippets.

@notuxic
Created August 28, 2014 19:02
Show Gist options
  • Save notuxic/5c27b6bed3019ceb8089 to your computer and use it in GitHub Desktop.
Save notuxic/5c27b6bed3019ceb8089 to your computer and use it in GitHub Desktop.
libSREV - a simple and clean way to add input regex validation to a html form
/*
* libSREV - Simple Regular Expression Validation
* ==============================================
*
* Author: notuxic
* Version: 0.1
* License: WTFPL (Do What The Fuck You Want To Public License)
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
*/
/*
* Usage:
* ------
* simply add a "rev" attribute with a ECMA-Script regular
* expression as value to the tag you want to validate.
*
* Example:
* --------
* Desired Format: yy-mm-dd
* <input type="text" rev="[0-99]{1}-[1-12]{1}-[1-31]{1}" name="date" />
*
* Styling:
* --------
* simply use the following two classes for styling a tag
* depending on the validation result:
* .rev-correct
* .rev-incorrect
*
* CSS-Tip:
* --------
* use the :focus selector to only style the active tag
* depending on the validation result.
*
*/
function validateRE() {
var activeelem = document.activeElement;
var pattern = new RegExp(activeelem.getAttribute('rev'),'m');
var string = activeelem.value;
var result = pattern.test(string);
if (result == true) {
activeelem.classList.remove('rev-incorrect');
activeelem.classList.add('rev-correct');
}
else {
activeelem.classList.remove('rev-correct');
activeelem.classList.add('rev-incorrect');
}
}
function registerREV() {
var taglist = document.getElementsByTagName('*');
for (i = 0; i < taglist.length; i++) {
if (taglist[i].getAttribute('rev')) {
taglist[i].addEventListener('keyup', validateRE, false);
}
}
}
registerREV();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment