Skip to content

Instantly share code, notes, and snippets.

@reichert621
Created September 9, 2018 04:51
Show Gist options
  • Save reichert621/1b4641ee90fcd07d1f5ab798f484943c to your computer and use it in GitHub Desktop.
Save reichert621/1b4641ee90fcd07d1f5ab798f484943c to your computer and use it in GitHub Desktop.
Refactoring 1
const moment = require('moment');
const isInputPresent = input => {
return input && typeof input === 'string' && input.trim().length > 0;
};
const isValidEmail = 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,}))$/;
return regex.test(String(email).toLowerCase());
};
const isValidName = name => {
return name.match(/^[a-zA-Z_ ]+$/);
};
const isValidBirthday = birthday => {
const date = moment(birthday, 'MM/DD/YYYY', true); // Enforce MM/DD/YYYY format
const today = moment();
return (
date.isValid() && date.isBefore(today) && date.diff(today, 'years') < 100
);
};
const handleValidations = inputs => {
const { name, email, birthday } = inputs;
const required = ['name', 'email', 'address', 'state', 'country', 'birthday'];
let errors = {};
required.forEach(field => {
const input = inputs[field];
if (!isInputPresent(input)) {
errors[field] = `${field} is required`;
}
});
if (!errors.email && !isValidEmail(email)) {
errors.email = 'Invalid email';
}
if (!errors.name && !isValidName(name)) {
errors.name = 'Invalid name';
}
if (!errors.birthday && !isValidBirthday(birthday)) {
errors.birthday = 'Invalid birthday';
}
return errors;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment