Last active
June 23, 2020 15:00
-
-
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)
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(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