Search code examples
javascriptnode.jsexpresspugexpress-validator

pug doesn't iterate array of object


i'm using express-validator and when i log my errors, everything is fine:

 errors:
   [ { value: '',
       msg: 'Email Field is empty',
       param: 'email',
       location: 'body' },
     { value: '',
       msg: 'Your email is not valid',
       param: 'email',
       location: 'body' } ] }

in my register.pug view:

   if(errors)
      .alert.alert-danger
          ul.mb-0
             each error in errors
                li=error.msg

this is my route:

router.post(
  "/register",
  [
    check("email")
      .notEmpty()
      .withMessage("Email Field is empty"),
    check("email")
      .isEmail()
      .withMessage("Your email is not valid")
  ],
  function(req, res) {
    const errors = validationResult(req);
    res.render("register", { errors });
  }
);

this is output: output image

it doesn't display error messages. can you help me?


Solution

  • Based on your console.log I think the errors variable is an object containing the key errors.

    So when you do each error in errors, error is equal to the errors array because the loop is indexing into the object instead of the array.

    This would mean that you'd have to change the res.render to either res.render("register", errors); or res.render("register", { errors: errors.errors });