Skip to content

Instantly share code, notes, and snippets.

@leodutra
Last active February 22, 2017 18:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leodutra/914cb99decb83315f134f557fcd5ca34 to your computer and use it in GitHub Desktop.
Save leodutra/914cb99decb83315f134f557fcd5ca34 to your computer and use it in GitHub Desktop.
Curried validation function for JavaScript
function validate(obj) {
function validator(prop) {
return function(validateFn) {
var res = validateFn(obj[prop])
if (!Array.isArray(res)) throw 'Validation function must return an array of arrays'
res.forEach(arr => {
if (!Array.isArray(arr)) throw prop + ' validation "' + JSON.stringify(arr) + '" requires a string as first item'
if (typeof arr[0] !== 'string') throw prop + ' validation "' + JSON.stringify(arr) + '" requires a string as first item'
})
var invalidation = res.find(propVal => !propVal[1])
if (invalidation) validator.invalids[prop] = invalidation[0] || '[Undefined invalidation message]'
return !invalidation;
}
}
validator.invalids = {}
validator.toString = function() {
return '[invalids ' + JSON.stringify(this.invalids) + ']';
}
return validator;
}
validation = validate({a:11212})
validation('a')(a => [
['A must be higher than 5', a > 5],
['A must be higher than 2000', a > 200000]
])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment