Skip to content

Instantly share code, notes, and snippets.

@mikaelbr mikaelbr/validator.js
Last active Jun 20, 2017

Embed
What would you like to do?
// 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
You can’t perform that action at this time.