Created
January 1, 2017 15:26
-
-
Save albertossilva/ec7154acb486598e1799fec403127970 to your computer and use it in GitHub Desktop.
Validating an object without 'if's
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
const validEmptyField = ({ field, label }) => ({ | |
match: (data) => { | |
const value = data && data[field] | |
return value === null || value === undefined || (typeof value === 'string' && value === '') | |
}, | |
message: () => `${label} is required` | |
}) | |
const validEmailConfirmation = { | |
match: ({ email, confirmationEmail }) => email && email !== confirmationEmail, | |
message: () => 'Email has to equal its confirmation' | |
} | |
const validIsAdult = { | |
match: ({ age }) => age && age < 19, | |
message: ({ age }) => `The age is ${age}, wait ${18 - age} years.` | |
} | |
const validators = [ | |
validEmptyField({ field: 'name', label: 'Name' }), | |
validEmptyField({ field: 'age', label: 'Age' }), | |
validEmptyField({ field: 'email', label: 'Email' }), | |
validIsAdult, | |
validEmailConfirmation | |
] | |
const bruno = { | |
name: 'Bruno', | |
age: 10, | |
email: 'bruno@empresadobruno.com', | |
confirmationEmail: 'bruno@empresadobruno.com' | |
} | |
const validate = (data, validators) => | |
validators | |
.filter(validator => validator.match(data)) | |
.map(validator => validator.message(data)) | |
.join(',') | |
console.log(validate(bruno, validators)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment