title: nodejs: express-validator errors undefined in ejs template
body: <p>I am using ejs engine instead of pug. When I click register button, I got errors undefined in my register view. There was only little chance that I can get the validation messages, but when I click other links and then back to the register page, the same error occurred  again.</p>
  
  <p>Here's my code:</p>
  
  <p><code>app.js</code></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//app.js code
  var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var session = require('express-session');
  var passport = require('passport');
  var expressValidator = require('express-validator');
  var LocalStrategy = require('passport-local').Strategy;
  var multer = require('multer');
  var upload = multer({dest: './uploads'});
  var flash = require('connect-flash');
  var mongo = require('mongodb');
  var mongoose = require('mongoose');
  var db = mongoose.connection;
   
  var routes = require('./routes/index');
  var users = require('./routes/users');
   
  var app = express();
   
  // view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');
   
  // uncomment after placing your favicon in /public
  //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
   
  // Handle Sessions
  app.use(session({
      secret:'secret',
      saveUninitialized: true,
      resave: true
  }));
   
  // Passport
  app.use(passport.initialize());
  app.use(passport.session());
   
  // Validator
  app.use(expressValidator({
      errorFormatter: function(param, msg, value) {
          var namespace = param.split('.')
              , root    = namespace.shift()
              , formParam = root;
   
          while(namespace.length) {
              formParam += '[' + namespace.shift() + ']';
          }
          return {
              param : formParam,
              msg   : msg,
              value : value
          };
      }
  }));
   
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));
   
  app.use(flash());
  app.use(function (req, res, next) {
      res.locals.messages = require('express-messages')(req, res);
      next();
  });
   
  app.use('/', routes);
  app.use('/users', users);
   
  // catch 404 and forward to error handler
  app.use(function(req, res, next) {
      var err = new Error('Not Found');
      err.status = 404;
      next(err);
  });
   
  // error handlers
   
  // development error handler
  // will print stacktrace
  if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
          res.status(err.status || 500);
          res.render('error', {
              message: err.message,
              error: err
          });
      });
  }
   
  // production error handler
  // no stacktraces leaked to user
  app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      res.render('error', {
          message: err.message,
          error: {}
      });
  });
   
   
  module.exports = app;</code></pre>
  </div>
  </div>
  </p>
  
  <p><code>user.js</code>
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//user.js code
  var express = require('express');
  var router = express.Router();
   
  var multer = require('multer');
  var upload = multer({dest: 'uploads/'});
  /* GET users listing. */
  router.get('/', function(req, res, next) {
    res.render('members', {page_name : 'members'});
  });
   
  router.get('/register', function(req, res, next) {
      res.render('register', { page_name: 'register' });
  });
   
  router.post('/register', upload.single('profileimage'), function(req, res) {
      var name = req.body.name;
      var username = req.body.username;
      var email = req.body.email;
      var password = req.body.password;
      var password2 = req.body.password2;
   
   
      if(req.file){
        console.log("uploading file");
        var profileimage = req.file.filename;
   
      } else{
          var profileimage = "noimage.jpg";
      }
   
   
      req.checkBody('name','Name field is required').notEmpty();
      req.checkBody('email','Email field is required').notEmpty();
      req.checkBody('email','Email is not valid').isEmail();
      req.checkBody('username','Username field is required').notEmpty();
      req.checkBody('password','Password field is required').notEmpty();
      req.checkBody('password2','Passwords do not match').equals(req.body.password);
   
      // Check Errors
   
       errors = req.validationErrors();
      //var errors = JSON.stringify(req.validationErrors());
   
      if(errors){
          console.log("errors: " + errors);
   
          res.render('register', {errors: errors});
      } else{
          console.log('No Errors');
          res.render("/");
      }
   
  });
   
  router.get('/login', function(req, res, next) {
      res.render('login', { page_name: 'login' });
  });
   
  module.exports = router;</code></pre>
  </div>
  </div>
  </p>
  
  <p><code>register.ejs</code>
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>//register.ejs code
   
  &lt;%include layout%&gt;
   
  &lt;div class="container"&gt;
   
  &lt;% if(errors){errors.forEach(function(error){%&gt;
   
      &lt;div class="alert alert-danger"&gt;&lt;%= error.msg %&gt;&lt;/div&gt;
   
   
      &lt;% })} %&gt;
   
      &lt;h4&gt;register&lt;/h4&gt;
   
      &lt;form action="/users/register" method="post" enctype="multipart/form-data"&gt;
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Name&lt;/label&gt;
              &lt;input type="text" class="form-control" name="name" placeholder="John"&gt;
          &lt;/div&gt;
   
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Email address&lt;/label&gt;
              &lt;input type="email" class="form-control" name="email" placeholder="name@example.com"&gt;
          &lt;/div&gt;
   
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Username&lt;/label&gt;
              &lt;input type="text" class="form-control" name="username" placeholder="username"&gt;
          &lt;/div&gt;
   
   
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Password&lt;/label&gt;
              &lt;input type="password" class="form-control" name="password" placeholder="password"&gt;
          &lt;/div&gt;
   
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Confirm Password&lt;/label&gt;
              &lt;input type="password" class="form-control" name="password2" placeholder="confirm password"&gt;
          &lt;/div&gt;
   
          &lt;div class="form-group"&gt;
              &lt;label for="exampleFormControlInput1"&gt;Profile Image&lt;/label&gt;
              &lt;input type="file" class="form-control" name="profileimage" &gt;
          &lt;/div&gt;
   
   
          &lt;button type="submit" class="btn btn-primary"&gt;Register&lt;/button&gt;
      &lt;/form&gt;
   
   
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p><code>Error</code>
  <div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>ReferenceError: /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/views/register.ejs:5
      3| &lt;div class="container"&gt;
      4| 
   &gt;&gt; 5|     &lt;% if(errors){errors.forEach(function(error){%&gt;
      6| 
      7|     &lt;div class="alert alert-danger"&gt;&lt;%= error.msg %&gt;&lt;/div&gt;
      8| 
   
  errors is not defined
      at eval (eval at compile (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:549:12), &lt;anonymous&gt;:22:8)
      at returnedFn (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:580:17)
      at tryHandleCache (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:223:34)
      at View.exports.renderFile [as engine] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:437:10)
      at View.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/view.js:127:8)
      at tryRender (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:640:10)
      at Function.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:592:3)
      at ServerResponse.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/response.js:971:7)
      at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/routes/users.js:12:9
      at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
      at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:137:13)
      at Route.dispatch (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:112:3)
      at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
      at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:281:22
      at Function.process_params (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:335:12)
      at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:275:10)</code></pre>
  </div>
  </div>
  </p>