Created
August 24, 2014 15:55
-
-
Save alenabdula/65a937c53d50427614b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
function Validator(rules) { | |
"use strict"; | |
this.patterns = {}; | |
this.tests = {}; | |
for (var i = 0; i < rules.length; ++i ) { | |
this.addRule(rules[i]); | |
} | |
}; | |
Validator.prototype.onChange = function(input, ruleName) { | |
"use strict"; | |
try { | |
if (typeof this.tests[ruleName] !== 'function') { | |
throw new Error('"'+ruleName+'" is not a rule'); | |
} | |
if (['INPUT','SELECT','TEXTAREA'].indexOf(input.tagName) === -1) { | |
throw new Error('[input] is not a form input'); | |
} | |
if (this.tests[ruleName](this.patterns[ruleName], input.value)) { | |
input.classList.remove('invalid'); | |
input.classList.add('valid'); | |
return true; | |
} | |
else { | |
input.classList.remove('valid'); | |
input.classList.add('invalid'); | |
return false; | |
} | |
} | |
catch(e){ console.log(e); } | |
}; | |
Validator.prototype.attachRule = function(input, rule) { | |
"use strict"; | |
input.addEventListener( | |
'keyup', | |
function(e) { | |
this.onChange.call(this, input, rule); }.bind(this), | |
false | |
); | |
}; | |
Validator.prototype.addRule = function(rule) { | |
this.patterns[rule.name] = rule.pattern; | |
this.tests[rule.name] = rule.test; | |
console.log(this); | |
} | |
var validatorRules = [ | |
{ | |
name: "required", | |
pattern: null, | |
test: function(pattern,value) { | |
return !!value; | |
} | |
}, | |
{ | |
name: "email", | |
pattern: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+[.][A-Za-z]{2,4}/, | |
test: function(pattern,value) { | |
return pattern.test(value); | |
} | |
}, | |
{ | |
name: "phone", | |
pattern: /[0-9]{3}[)]?[-. ]?[0-9]{3}/, | |
test: function(pattern,value) { | |
return pattern.test(value); | |
} | |
} | |
]; | |
var validator = new Validator(validatorRules); | |
Array.prototype.slice.call( | |
document.querySelectorAll('[data-validator]')).forEach(function(input) { | |
validator.attachRule(input ,input.getAttribute('data-validator')); | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment