I've spent the past few days trying to figure this out without success. I'm wanting to only preventdefault if it fails. I'm assuming the form wont submit because it's preventdefault either way. Thanks.
form.addEventListener("submit", (e)=>{
e.preventDefault();
engine(username, 0, "Name cannot be blank");
engine(email, 1, "Email cannot be blank");
engine(message, 2, "Message cannot be blank");
})
let engine = (id, serial, message) =>{
if(id.value.trim() === ""){
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opaity = "1";
successIcon[serial].style.opacity = "0";
}
else{
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0"
successIcon[serial].style.opacity = "1";
}
CodePudding user response:
You need to make your function return a flag to indicate whether it succeeded or not, and then use that flag in your event handler, for example:
form.addEventListener("submit", (e) => {
let valid = true;
valid &&= engine(username, 0, "Name cannot be blank");
valid &&= engine(email, 1, "Email cannot be blank");
valid &&= engine(message, 2, "Message cannot be blank");
if (!valid) {
e.preventDefault();
}
});
const engine = (id, serial, message) => {
if (id.value.trim() === "") {
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opacity = "1"; // Fixed typo on this line
successIcon[serial].style.opacity = "0";
return false;
}
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0";
successIcon[serial].style.opacity = "1";
return true;
};
I've used &&=
there because it makes sense to show all the invalid things rather than just the first, which is what you'd get if you just did const valid = engine(/*...*/) && engine(/*...*/) && engine(/*...*/);
.
CodePudding user response:
So, make the validation function engine
to return a flag true
if valid and false
if not valid, and use every
method to check that all are valid.
form.addEventListener("submit", (e)=>{
const valid = [engine(username, 0, "Name cannot be blank"),
engine(email, 1, "Email cannot be blank"),
engine(message, 2, "Message cannot be blank")].every(v => v)
if (!valid) {
e.preventDefault();
}
})
let engine = (id, serial, message) =>{
if(id.value.trim() === ""){
errorMsg[serial].innerHTML = message;
faulureIcon[serial].style.opaity = "1";
successIcon[serial].style.opacity = "0";
return false;
} else {
errorMsg[serial].innerHTML = "";
faulureIcon[serial].style.opacity = "0"
successIcon[serial].style.opacity = "1";
return true;
}