Skip to content

Instantly share code, notes, and snippets.

@reichert621
Created September 9, 2018 05:11
Show Gist options
  • Save reichert621/16b5c7b8f7647dad702dfd01b6cacd60 to your computer and use it in GitHub Desktop.
Save reichert621/16b5c7b8f7647dad702dfd01b6cacd60 to your computer and use it in GitHub Desktop.
Refactoring 2
const getValidators = () => {
return [
{
field: 'name',
validations: [
[isInputPresent, 'Name is required'],
[isValidName, 'Invalid name']
]
},
{
field: 'email',
validations: [
[isInputPresent, 'Email is required'],
[isValidEmail, 'Invalid email']
]
},
{
field: 'address',
validations: [[isInputPresent, 'Address is required']]
},
{
field: 'state',
validations: [[isInputPresent, 'State is required']]
},
{
field: 'country',
validations: [[isInputPresent, 'Country is required']]
},
{
field: 'birthday',
validations: [
[isInputPresent, 'Date of birth is required'],
[isValidBirthday, 'Invalid date of birth']
]
}
];
};
const handleValidations = inputs => {
const validators = getValidators();
return validators.reduce((result, { field, validations }) => {
const input = inputs[field];
return validations.reduce((acc, [isValid, err]) => {
if (!acc[field] && !isValid(input)) {
return {
...acc,
[field]: err
};
} else {
return acc;
}
}, result);
}, {});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment