Skip to content

Instantly share code, notes, and snippets.

@skinnyjames
Created January 7, 2017 21:08
Show Gist options
  • Save skinnyjames/4fce84b7718a7ea5d68ece96d6e2d304 to your computer and use it in GitHub Desktop.
Save skinnyjames/4fce84b7718a7ea5d68ece96d6e2d304 to your computer and use it in GitHub Desktop.
validator.js
validator = new Validator({
presence: ['address', 'email', 'password', 'password_confirmation'],
regex: {
email: '[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}'
},
length: {
password: '> 10',
password_confirmation: '> 10'
},
custom: [
function(obj){
return [obj.password === obj.password_confirmation, 'passwords don\'t match'];
},
]
});
validator.validate({password: 'hello', password_confirmation: 'world'});
modules.exports = function(){
class Validator{
constructor(rules){
this.rules = rules;
this.errors = [];
}
validate(things){
// validate presence
this.errors = [];
if(this.rules.presence && this.rules.presence.length > 0){
for(let i=0;i<this.rules.presence.length;i++){
if(!things[this.rules.presence[i]]){
this.errors.push(this.rules.presence[i] + ' must be present');
}
}
}
// validate regex
if (this.rules.regex){
for(let x in this.rules.regex){
if(things[x] && !things[x].match(this.rules.regex[x])){
this.errors.push(x + ' is invalid');
}
}
}
// validate length
if (this.rules['length']){
for(let x in this.rules['length']){
let [symbol, value] = this.rules['length'][x].split(' ')
switch(symbol){
case '=':
if(!things[x].length === value){
this.errors.push(x + ' must be ' + value + ' characters long');
break;
}
case '>':
if(!things[x].length > value){
this.errors.push(x + ' must be greater than ' + value + ' characters');
break;
}
case '<':
if(!(things[x].length < value)){
this.errors.push(x + ' must be less than ' + value + ' characters');
break;
}
}
}
}
//validate custom functions
if (this.rules.custom && this.rules.custom.length > 0){
for(let i=0;i<this.rules.custom.length; i++){
let[test,msg] = this.rules.custom[i](things);
if(!test){
this.errors.push(msg);
}
}
}
// return errors if there are any
if(this.errors){
return this.errors ;
}else{
return null;
}
}
}
return Validator;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment