0

My 'errors' variable in ejs template causes 'undefined' error on page load

I have an ejs template for a contact-form with code to output errors via flash messages to the page when the form is not properly or completely filled out.

<%- messages('message', locals) %>

    <% if (errors !== undefined) { %>
    // Output the errors to the page
    <% errors.forEach(function(error) { %>
        <div class="alert alert-danger">
            <%= error.message %>
        </div>
    <% }) %>
<% } %>

The code in my app.js file creates the 'errors' variable.

let errors = req.validationResult();

if (errors) {
    res.render('contact-form', {
        errors: errors
    });

For what it's worth, the 'messages.ejs' template contains the following code:

<div id="messages">
<% Object.keys(messages).forEach(function (type) { %>
    <div class="alert alert-<%= type %>">
    <% messages[type].forEach(function (message) { %>
        <p><%= message %></p>
    <% }) %>
    </div>
<% }) %>
</div>

The line:

<% if (errors !== undefined) { %>

from the contact-form.ejs template is throwing the 'errors is not defined' error.

Todd Brannon
  • 182
  • 3
  • 16
  • 2
    Possible duplicate of [What is the proper way to check for existence of variable in an EJS template (using ExpressJS)?](https://stackoverflow.com/questions/5372559/what-is-the-proper-way-to-check-for-existence-of-variable-in-an-ejs-template-us) – Claies Dec 31 '18 at 04:39

1 Answers1

0

My guess is that "undefined error" is referring to errors.forEach. The result of validationResult() is not an array of errors, it's an object with getters like isEmpty() and array(), so you may need to adjust your controller code slightly.

Check out the docs for some examples.

Elliot Nelson
  • 11,371
  • 3
  • 30
  • 44