I am using express-validator for form validation and using axios to send the data to to the server. Once the validation is done I send a response back. I can loop over the errors and display them all in console, one under another but in my error div where I want to show the errors to the user, it only shows one, instead of all of them like in console.
Controller:
if (!errors.isEmpty()) {
return res.status(422).json({error: errors.array()});
}
Display errors to user:
const errorLoop = error.response.data.error;
for (const errMsg of errorLoop) {
console.log(errMsg.msg);
const showError = document.querySelector('.error');
showError.classList.add("notification");
showError.innerHTML = errMsg.msg;
}
You are setting the innerHTML for each error. Thus you are replacing it and will only ever see the last error.
Try this:
let errorMessages = ""
for(const errMsg of errorLoop){
errorMessages += errMsg.msg + "<br>"
}
const showError = document.querySelector('.error')
showError.classList.add("notification")
showError.innerHTML = errorMessages
(The <br>
will insert a new line for visual purposes)