Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Last active June 20, 2017 06:59
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 mikaelbr/3c42c6561f87fab1eaa5cb7e3323c161 to your computer and use it in GitHub Desktop.
Save mikaelbr/3c42c6561f87fab1eaa5cb7e3323c161 to your computer and use it in GitHub Desktop.
// 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