JSFiddle - React, Tailwind, and code Playground
by Darby Rathbone
HTML
<input type="text" id='in' data-validator="^\D*(\d\d)?\D*(\d\d)?\D*(\d\d)?\D*" data-validparse="$1 - $2 - $3" />
JavaScript
/*document.getElementById('in').addEventListener('input', function (e) {
console.log(e);
console.dir(e);
e.preventDefault();
e.target.value = "";
});
*/
var validator = function (e) {
return function () {
if (typeof this.regexp == 'undefined' || this.regexp.source.toString() !== this.dataset['validator'].replace(/\\/g, '\\')) {
this.regexp = new RegExp(this.dataset['validator'].replace(/\\/g, '\\'), 'gi');
}
if (this.regexp.test(this.value)) {
this.classList.remove('error');
} else {
if (!this.regexp.test(this.value)) {
this.classList.add('error');
}
}
}.bind(e.target)();
};
var validparse = function (e) {
return function () {
console.log(e.target);
if (typeof this.regexp == 'undefined' || this.regexp.source.toString() !== this.dataset['validator'].replace(/\\/g, '\\')) {
this.regexp = new RegExp(this.dataset['validator'].replace(/\\/g, '\\'), 'gi');
}
console.log(e.target.value.replace(this.regexp, this.dataset['validparse']));
e.target.value = e.target.value.replace(this.regexp, this.dataset['validparse']);
console.log(this.dataset['validparse'].replace(/\w[\$](\d+)/g, function (g, m) {
return e.target.value.split(this.regexp).filter(Boolean)[m];
}));
}.bind(e.target)();
};
var submit = function (btn) {
return [].slice.call(document.forms).filter(function (e) {
return e.contains(btn)
}).every(function (f) {
var firsterror = f.querySelector('.error');
if (firsterror) {
firsterror.scrollIntoViewIfNeeded();
firsterror.focus();
return false;
}
return true;
}.bind(btn));
};
[].slice.call(document.querySelectorAll('[data-validator]')).forEach(function (e) {
e.addEventListener('input',...