S
S
SpideR-KOSS2018-08-19 15:42:43
JavaScript
SpideR-KOSS, 2018-08-19 15:42:43

Output Express validation error to HBS template?

Hello!
Connected the Express-Validator.
Set up field validation.

check('username').isEmail(),
check('password').isLength({ min: 5 });

How can I pass the form validation error to the HBS template now?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksey Solovyev, 2018-08-19
@SpideR-KOSS

// ...rest of the initial code omitted for simplicity.
const { check, validationResult } = require('express-validator/check');

app.post('/user', [
  // username must be an email
  check('username').isEmail(),
  // password must be at least 5 chars long
  check('password').isLength({ min: 5 })
], (req, res) => {
  // Finds the validation errors in this request and wraps them in an object with handy functions
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(422).json({ errors: errors.array() });
  }

  User.create({
    username: req.body.username,
    password: req.body.password
  }).then(user => res.json(user));
});

{
  "errors": [{
    "location": "body",
    "msg": "Invalid value",
    "param": "username"
  }]
}

errors.array() are your errors. Pass them to your template -res.render('home', {errors: errors.array()});
{{# if errors }}
    {{# each errors }}
          <p class="alert alert-danger">{{ this.msg }}</p>
    {{/each}}
{{/if}}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question