Skip to content

Instantly share code, notes, and snippets.

@albertossilva
Created January 1, 2017 15:26
Show Gist options
  • Save albertossilva/ec7154acb486598e1799fec403127970 to your computer and use it in GitHub Desktop.
Save albertossilva/ec7154acb486598e1799fec403127970 to your computer and use it in GitHub Desktop.
Validating an object without 'if's
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