I am trying to validate the email input box to return an error when it is empty or when it does not match the email regex pattern. If email input is empty I should get an error and if email input is not empty but does not meet the pattern I should get a new error. So far I am only getting one error
const form = document.querySelector("form"),
user = document.getElementById("name"),
email = document.getElementById("email"),
emailField = document.getElementById("email-field"),
msg = document.getElementById("comment"),
errorMsg = document.getElementsByClassName("error"),
container1 = document.getElementById("form-container"),
container2 = document.getElementById("form-container2");
let field = (id, serial, message) => {
if (id.value.trim() === "") {
errorMsg[serial].innerHTML = message;
id.classList.add("invalid");
} else {
errorMsg[serial].innerHTML = "";
id.classList.remove("invalid");
}
}
// Email Validtion
function checkEmail() {
const emaiPattern = /^[^ ]+@[^ ]+\.[a-z]{2,3}$/;
if (!email.value.match(emaiPattern)) {
console.log("no match");
errorMsg[1].innerHTML = "message";
// email.classList.add("invalid"); //adding invalid class if email value do not mathced with email pattern
} else {
console.log("matches");
// emailField.classList.remove("invalid"); //removing invalid class if email value matched with emaiPattern
}
}
form.addEventListener("submit", (e) => {
e.preventDefault();
field(user, 0, "Name cannot be blank");
field(email, 1, "Email cannot be blank");
field(msg, 2, "Message cannot be blank");
checkEmail();
if (!user.classList.contains("invalid") &&
!email.classList.contains("invalid") &&
!msg.classList.contains("invalid")
) {
location.href = form.getAttribute("action");
container1.classList.add("hide");
container2.classList.remove("hide");
}
});
<div class="form-field">
<input type="text" id="email" placeholder="Email Address">
<div class="error"></div>
</div>