Eye Patch
Eye Patch

Reputation: 991

How to get validation errors with expres-validator?

I have just started learning express-validator. I have read the docs of express-validator, but my question might have an answer in these docs which I didn't totally understand. I want to check some values, but I don't know how to get the errors in case of the the values didn't match the validation.

const { check, validationResult } = require('express-validator/check');
const router = require("express").Router();

router.post("/", (req, res, next)=>{
    // validate user input
    const username = req.body.username;
    const email = req.body.email;
    const password = req.body.password;

    check("username")
    .not().isEmpty().withMessage("Username must not be empty!");
    check("email")
    .not().isEmpty().withMessage("Email must not be empty!");
    check("password")
    .not().isEmpty().withMessage("Password must not be empty!");

    //Get check results
});
module.exports = router;

Also, does the check() return a promise or does it run synchronously? And, in the docs there is:

app.post('/user', [
  check('username').isEmail()], (req, res) => {
  const errors = validationResult(req);
  ...
  }

I have tried validationResult(req) but it gives me an object with some functions where only isEmpty() is true while the other functions are weather false, null, or undefined. And why is ther an array in the post method?

Thank you in advance

Upvotes: 0

Views: 948

Answers (1)

Yannick K
Yannick K

Reputation: 5422

Example from the docs:

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

If you want your code to work, you have to follow the same structure.

If validationResult finds any errors, your server will response with this:

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

In your case you can directly copy the code from this docs example and it will work fine.

Upvotes: 1

Related Questions