@viniciusvalmeidaSubmitted about 1 year ago
Is there a different way than not use so many "Ifs" in validation?
Is there a different way than not use so many "Ifs" in validation?
Hi viniciusvalmeida,
Nice work on this challenge, well done. Here are some few observations: It is not good practice to use getElementById in React for several reasons:
About your question, yes there is a way to avoid those ifs.👌🏻
const getElement = (id) => document.getElementById(id);
const showError = (input, label, msg) => {
input.classList.add("border-primary-light-red");
label.classList.add("text-primary-light-red");
msg.innerHTML = "This field is required";
msg.classList.remove("invisible");
};
const resetErrors = (inputs, labels, msgs) => {
inputs.forEach((input) => input.classList.remove("border-primary-light-red"));
labels.forEach((label) => label.classList.remove("text-primary-light-red"));
msgs.forEach((msg) => msg.classList.add("invisible"));
};
const checkDateValidity = (day, month, year) => {
const currentDate = new Date();
return (
+year > currentDate.getFullYear() ||
(+year === currentDate.getFullYear() && +month > currentDate.getMonth() + 1) ||
(+day > currentDate.getDate() && +year === currentDate.getFullYear() && +month > currentDate.getMonth())
);
};
const handleSubmit = (ev) => {
ev.preventDefault();
const dayInput = getElement("day");
const monthInput = getElement("month");
const yearInput = getElement("year");
const dayLabel = getElement("dayLabel");
const monthLabel = getElement("monthLabel");
const yearLabel = getElement("yearLabel");
const dayMsg = getElement("dayMsg");
const monthMsg = getElement("monthMsg");
const yearMsg = getElement("yearMsg");
const inputs = [dayInput, monthInput, yearInput];
const labels = [dayLabel, monthLabel, yearLabel];
const msgs = [dayMsg, monthMsg, yearMsg];
resetErrors(inputs, labels, msgs);
if (!birthDay) {
showError(dayInput, dayLabel, dayMsg);
return false;
}
if (!birthMonth) {
showError(monthInput, monthLabel, monthMsg);
return false;
}
if (!birthYear) {
showError(yearInput, yearLabel, yearMsg);
return false;
}
if (birthMonth in thirtyDayMonths && birthDay === "31") {
showError(dayInput, dayLabel, dayMsg);
return false;
}
if (checkDateValidity(birthDay, birthMonth, birthYear)) {
showError(yearInput, yearLabel, yearMsg);
return false;
}
setDay(birthDay);
setMonth(birthMonth);
setYear(birthYear);
};
This way the code is more readable.