I am using nodejs, ejs, express, & express-validator. I am trying to use express validator on my registration page (signup,ejs). Express-validator generates the errors in an array of objects. When I console.log the results (in var errors) I get:
formatter: [Function: formatter],
errors:
[ { value: 'kl',
msg: 'Username must be between 4 and 15 characters.',
param: 'username',
location: 'body' },
{ value: 'kl',
msg: 'Password must be between 8 and 100 characters.',
param: 'password',
location: 'body' },
{ value: 'klsdflksdf',
msg: 'Passwords must match.',
param: 'confirmPassword',
location: 'body' } ] }
When I try to iterate the array on my view page (signup.ejs) using For Of I get the error that err is not iterable. When I use For In (shown below), the result is two items showing on my view page. the first is Fromatoer and the second is errors. How do I get the msg: valuse showing? replacing with <% errors.msg %> produces nothing on the views page.
Here is my views page:
<%- include('includes/navigation.ejs') %>
<% if (typeof errors !== "undefined") { %>
<p>there are errors on page</p>
<% for(const error in errors) { %>
<div class="alert alert-warning">
<li> <%= error %> </li>
</div>
<% } %>
<% } %>
<div class="container">
<form class="signup-form" action="/signup" method="POST">
<div class="form-group">
<label for="username">Username</label>
<input type="text" class="form-control" id="username" name="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Password">
</div>
<div class="form-group">
<label for="confirmPassword">Confirm Password</label>
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword"
placeholder="Confirm Password">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
Here is my Controller:
exports.postSignup = [
check('username', 'Username field must not be empty.').not().isEmpty(),
check('username', 'Username must be between 4 and 15 characters.').isLength(4, 15),
check('password', 'Password must be between 8 and 100 characters.').isLength(8, 100),
check('confirmPassword', 'Passwords must match.').equals('password'),
(req, res, next) => {
const username = req.body.username;
const password = req.body.password;
const confirmPassword = req.body.confirmPassword;
const errors = validationResult(req);
if (errors) {
console.log(errors);
res.render('signup', {
pageTitle: 'Registration Error',
errors: errors
});
} else {
User.create({
username: req.body.username,
password: req.body.password
})
.then(result => {
res.render('login', { pageTitle: "Signup Successfull" });
})
.catch(err => console.log(err));
};
}
];
for inis meant to be used for iteration over object properties and not best for use with Arrays. For thatArray.forEachorfor ofis better.