1

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));
        };
    }
];

1
  • Just a suggestion. for in is meant to be used for iteration over object properties and not best for use with Arrays. For that Array.forEach or for of is better. Commented Oct 11, 2019 at 11:44

1 Answer 1

0

The way you check if any validation error exist should be different. After this line of code you do not get the iterable array.

const errors = validationResult(req);

You need to use isEmpty() method to check if any error exist; and array() method to convert errors to iterable array. Typically error handlers look like:

const errorHandler = (req, res, next) => {
    let errors = validationResult(req);
    if (!errors.isEmpty()) {
        errors = errors.array();
        // some other stuff
    } else next();
};

Source: express-validator docs

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.