Skip to content

Instantly share code, notes, and snippets.

@drslump
Created February 14, 2011 20:09
Show Gist options
  • Save drslump/826447 to your computer and use it in GitHub Desktop.
Save drslump/826447 to your computer and use it in GitHub Desktop.
a prof of concept for "Transfer Objects" or "Parameter Objects"
function field() {
var type = 'string',
optional = false,
regexp = null,
custom = null;
return {
'string': function(){ type = 'string'; return this },
'int': function(){ type = 'number'; return this },
'optional': function(){ optional = true; return this },
'required': function(){ optional = false; return this },
'match': function(exp){ regexp = exp; return this },
'custom': function(fn){ custom = fn; return this },
isValid: function(v){
if (typeof v === 'undefined') return optional;
if (typeof v !== type) return false;
if (regexp && !regexp.test(v)) return false;
if (custom && !custom(v)) return false;
return true;
},
getErrorMessage: function(v){
if (typeof v === 'undefined' && !optional)
return 'Required but missing';
if (typeof v !== type)
return 'Expecting type ' + (type) + ' but got ' + (typeof v);
if (regexp && !regexp.test(v))
return 'Did not match ' + regexp.toString();
if (custom && !custom(v))
return 'Did not pass custom validation';
return this.isValid(v) ? 'Ok' : 'Unknown error';
}
};
}
function validate(rules, hashmap){
var errors = [],
hashmap = hashmap || {};
// Augment the hashmap with validation methods
hashmap.checkRules = function(){
errors = [];
for (var name in rules) if (rules.hasOwnProperty(name)) {
if (!rules[name].isValid(this[name])) {
errors.push(
'Field "' + name + '" is not valid: ' +
rules[name].getErrorMessage(this[name])
);
}
}
return errors;
};
hashmap.isValid = function(){
errors = this.checkRules();
return errors.length === 0;
};
hashmap.getErrors = function(){
return errors;
};
return hashmap;
}
// Define the validation rules
var rules = {
name: field().match(/^[A-Za-z]+$/),
age: field().int().optional().custom(function(v){ return v > 18 && v < 67 })
};
// Assign values by "hashmap"
var req = {
name: 'Ivan'
};
var obj = validate(rules, req);
// Also assign values 'interactively'
obj.age = 23;
// Validation is OK
if (!obj.isValid()) {
alert(obj.getErrors());
} else {
alert('Ok');
}
// Make it fail
obj.name = 'Iván';
if (!obj.isValid()) {
alert(obj.getErrors());
} else {
alert('Ok');
}
// Check a single field validation
alert(rules.name.getErrorMessage('Iván'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment