Issue
Is there a way that I can shorten this code. They have similar condition but different codes to execute. the first one is when I keydown the element will show or hide, the second one after I click the button or submit the form, it will stop or pass the user.
textInput.addEventListener("keydown", function myFunction(){
if(textInput.value.match(characters)){
invalidFeedback.style.display = "block";
}
else if (textInput.value === ""){
invalidFeedback.style.display = "block";
} else {
invalidFeedback.style.display = "none";
}
});
form.addEventListener("submit", function (event, myFunction){
if(textInput.value.match(characters)){
event.preventDefault();
}
else if (textInput.value === ""){
event.preventDefault();
}
});
Solution
When multiple conditional statements have the same outcome, we can use the ||
operator, which is like "OR".
We can also export common checks to functions, to keep things granular, neat, and easy-to-consume.
Finally, in the "keydown" event, I introduced a guard clause, which returns the desired outcome on a satisfied condition. It’s much easier to read than nested if/else statements.
const doesMatch = () => textInput.value.match(characters);
const isEmpty = () => textInput.value === "";
textInput.addEventListener("keydown", () => {
if (doesMatch() || isEmpty())
return invalidFeedback.style.display = "block";
invalidFeedback.style.display = "none";
});
form.addEventListener("submit", (event) => {
if (doesMatch() || isEmpty()) event.preventDefault();
});
Answered By – Rida F'kih
Answer Checked By – Candace Johnson (BugsFixing Volunteer)