Skip to content

Instantly share code, notes, and snippets.

@reichert621
Last active September 12, 2018 07:09
Show Gist options
  • Save reichert621/8339a8cec7ce6984b8c21f4c698aed66 to your computer and use it in GitHub Desktop.
Save reichert621/8339a8cec7ce6984b8c21f4c698aed66 to your computer and use it in GitHub Desktop.
Refactoring #0
const handleValidations = inputs => {
const { name, email, birthday } = inputs;
const required = ['name', 'email', 'address', 'state', 'country', 'birthday'];
let errors = {};
for (let i = 0; i < required.length; i += 1) {
const val = required[i];
if (inputs[val].length < 1) {
errors[required[i]] = `${val} is required.`;
}
}
if (!errors.email) {
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (!regex.test(String(email).toLowerCase())) {
errors.email = 'Invalid email';
}
}
if (!errors.name) {
if (!name.match(/^[a-zA-Z_ ]+$/)) {
errors.name = 'Invalid name';
}
}
if (!errors.birthday) {
const date = new Date(birthday);
const today = new Date();
if (
!date ||
birthday.length < 10 ||
date.getFullYear() > today.getFullYear() ||
date.getFullYear() < today.getFullYear() - 100
) {
errors.birthday = 'Invalid birthday';
}
}
return errors;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment