When re-rendering my form with any errors, I am able to display the errors in a list. However, I would like to access each error individually to display them under the invalid input instead of all at the bottom of the form.
Here is what I have tried so far:
// controller.js
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render("quotes", {
form: req.body,
errors: errors.array()
});
return;
}
// ejs file
<% if (locals.errors) { %>
<ul>
<% errors.forEach(error => { %>
<li><%= error.msg %></li>
<% }) %>
</ul>
<% } %>
However, this solution displays all errors in a list format rather than individually under each invalid input. Below is my attempt to show errors individually:
//controller.js
(req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render("quotes", {
form: req.body,
errors: errors.array(),
error1: errors.array()[0].msg,
error2: errors.array()[1].msg,
error3: errors.array()[2].msg
});
return;
}
// ejs file
<% if (locals.errors) { %> <li> <%= error1 %></li> <% } %>
errors: [
{
value: '',
msg: 'First name must be specified',
param: 'firstName',
location: 'body'
},
{
value: '',
msg: 'Last name must be specified',
param: 'lastName',
location: 'body'
},
{
value: '',
msg: 'Please enter a valid email',
param: 'email',
location: 'body'
}
]
Any guidance or suggestions on how to achieve displaying errors individually under each invalid input would be greatly appreciated!