Hi, I played a bit with your solution and came up with an idea of how to make it work. The problem is that you are using .checkValidity() method to find out whether the form is valid but it doesn't work as you expect, because this method validates the form based on the attributes you use in inputs, like required
or min / max
. But since you don't use any of them (and for this particular project you don't need to use them), checkValidity() doesn't actually validate anything. So, you need to create your own validation logic for this.
So, here is how I solved it: first, I deleted your validation if statement (this one):
if (form.checkValidity()) {
showSuccess()
}
and wrote the checkFormValidity function which loops through your error messages and sets formIsValid to true if all the error messages have "hide" class (thus they're all valid), and false if even one of the messages doesn't have the "hide" class. It also resets the form in case it is valid (according to the challenge requirements)
const errorMessages = document.querySelectorAll(".error-message");
let formIsValid = false; // these should go to the global scope at the top of the page
function checkFormValidity() {
for (let message of errorMessages) {
if (!message.className.includes("hide")) {
formIsValid = false;
break;
}
formIsValid = true;
}
if (formIsValid) {
form.reset();
}
}
also I deleted your showSuccess function and instead made showSuccessIfFormIsValid which shows the message if the form is valid and hides it otherwise:
const success = document.querySelector(".success"); // this should go to the global scope at the top of the page
function showSuccessIfFormIsValid() {
if (formIsValid) {
success.style.display = "flex";
} else {
success.style.display = "none";
}
}
Now you include checkFormValidity() and showSuccessIfFormIsValid() to form submission event and it should work:
form.addEventListener("submit", (e) => {
e.preventDefault();
validateInputs();
checkFormValidity();
showSuccessIfFormIsValid();
});
As to the problem with inputs being pushed up by the error messages: you can just use position absolute for the messages, thus they won't influence the layout.
I tried to be as detailed as possible, but if my explanation is not good enough, you can always ask additional questions. Good luck!