Last active
June 20, 2017 06:59
-
-
Save mikaelbr/3c42c6561f87fab1eaa5cb7e3323c161 to your computer and use it in GitHub Desktop.
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
// pick is something ala lodash pick (fetching nested values from objects), but in it's simplest case | |
function pick (name, obj) { | |
return obj[name]; | |
} | |
function validate (name, predicate, message, obj) { | |
if (!predicate(pick(name, obj))) { | |
return { valid: false, message, name }; | |
} | |
return { valid: true, name }; | |
} | |
function partial (fn, args) { | |
return function (innerArgs) { | |
return fn(...args.concat(innerArgs)); | |
} | |
} | |
function isEmpty (input) { | |
return typeof input === "undefined" || input === ''; | |
} | |
function generateValidationObject (fns, obj) { | |
return fns.reduce(function (validObject, fn) { | |
const { valid, name, message } = fn(obj); | |
if (valid) return validObject; | |
const hasArray = Array.isArray(validObject[name]); | |
validObject[name] = hasArray ? validObject[name].concat(message) : [message]; | |
return validObject; | |
}, {}); | |
} | |
export default function validator (fields = []) { | |
return { | |
notEmpty (name) { | |
const validationFunc = partial(validate, name, isEmpty, `${name} is required input`); | |
return validator(fields.concat(validationFunc)); | |
}, | |
isValid (obj) { | |
return generateValidationObject(fields, obj); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment