Last active
February 22, 2017 18:04
-
-
Save leodutra/914cb99decb83315f134f557fcd5ca34 to your computer and use it in GitHub Desktop.
Curried validation function for JavaScript
This file contains 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 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