Skip to content

Instantly share code, notes, and snippets.

@park-brian
Last active June 23, 2020 15:00
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 park-brian/57c058c599103463806ecd5316a34129 to your computer and use it in GitHub Desktop.
Save park-brian/57c058c599103463806ecd5316a34129 to your computer and use it in GitHub Desktop.
A simple utility to validate objects (based off the Angular validation api)
function validate(object, rules) {
return Object.entries(object).reduce((errors, [key, value]) => {
let validators = rules[key];
if (!validators || validators.length === 0)
return errors;
if (typeof validators === 'function')
validators = [validators];
validators
.map(validator => validator(value, object, key)) // run validators against the current value
.filter(result => result.error) // select validation errors
.forEach(result => errors[key] = { // merge validation errors into the accumulator
...errors[key],
[result.error]: result.message
});
return errors;
}, {});
}
function required(value) {
const isValid = value !== undefined && value !== null && value !== '';
return isValid || {error: 'required', message: `Please enter a value`};
}
function range(min, max, exclusive) {
return function(value) {
const skip = value === undefined || value === null || value === '';
const isValid = skip || (
exclusive
? (value > min && value < max)
: (value >= min && value <= max)
);
return isValid || {error: 'range', message: `Please enter a value between ${min} and ${max}`};
};
}
function pattern(regex) {
return function(value) {
const skip = value === undefined || value === null;
const isValid = skip || regex.test(value);
return isValid || {error: 'pattern', message: `Please enter a value which matches the specified format`}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment