I was looking for a way to elegantly validate properties on a javascript object and came across this solution made by Patrick Roberts:
Javascript - elegant way to check object has required properties
const schema = { name: value => /^([A-Z][a-z\-]* )+[A-Z][a-z\-]*( \w+\.?)?$/.test(value), age: value => parseInt(value) === Number(value) && value >= 18, phone: value => /^(\+?\d{1,2}-)?\d{3}-\d{3}-\d{4}$/.test(value) }; let info = { name: 'John Doe', age: '', phone: '123-456-7890' }; const validate = (object, schema) => Object .keys(schema) .filter(key => !schema[key](object[key])) .map(key => new Error(`${key} is invalid.`)); const errors = validate(info, schema); if (errors.length > 0) { for (const { message } of errors) { console.log(message); } } else { console.log('info is valid'); } This solution can only return a generic error message return new Error(key + " is invalid")
How could I modify this solution to give a more specific error message?
An example would be if the age on the info object was set to 17:
let info = { name: 'John Doe', age: '17', phone: '123-456-7890' }; then the error message would be "Age must be above 18" and if it was set to 100, the error message would be "Age must be below 100"