node.jsejsexpress-validator

How to display express validator errors in a div


I'm using express validator to validate a form and I'm able to get the results however, I'm not sure how to display it into my EJS file.

        const errors = validationResult(req);
        if (!errors.isEmpty()) {
           let error = errors.array().map(i => `${i.msg}`).join(' ');
           res.render('sell', { title: 'Sell', error: errors });
        }

ejs file

                    <% if (error != null) { %>
                        <div class="alert alert-danger">
                                <%= error %>
                        </div>

                            <% } %>

This code only returns the errors on one line, I want it to display the errors in its own alert div.


Solution

  • create a for loop for errors like this

    <% if (error !=null) { %>
        <% for (const err of error) { %>
          <div class="alert alert-danger">
            <%= err %>
          </div>
        <% } %>
    <% } %>
    

    and I would actually rename it to errors since it's plural