Umakanth Pendyala
Umakanth Pendyala

Reputation: 335

Express-validator is not producing errors, even though it should produce

I am using express-validator package and I tried to validate the data before I insert it into the database but for some reason, the data is not being validated and inserted directly into the database.

Here is my code file.

router.post(
  "/signup",
  [
    check("name")
      .isLength({ min: 3 })
      .withMessage("name should be atleast 2 chars"),
    check("email").isEmail().withMessage("email is required"),
    check("password")
      .isLength({ min: 3 })
      .withMessage("password should be atleast 2 chars"),
  ],
  signup
);


const signup = (req, res) => {

  const errors = validationResult(req);

  if (!errors.isEmpty) {
    res.status(422).json({
      error: errors.array()[0].msg,
    });
    return;
  } 

  const user = new User(req.body);
  user.save((err, user) => {
    if (err) return res.send("database injection failed error code 400");
    return res.json(user);
  });
};

if I give the input as

{
    "name": "jo",
    "email": "[email protected]",
    "password": "kdfjldkmcs"
}

Upvotes: 1

Views: 57

Answers (1)

Raphael Serota
Raphael Serota

Reputation: 2197

I haven't tried running your code, but I can see at least one thing that looks out of place. In your code, you check if (!errors.isEmpty) {, but in the official example from the docs, it's checked like this: if (!errors.isEmpty()) {.

errors.isEmpty is a function that returns true or false, indicating if there were any errors. Since it's a function, simply checking if (!errors.isEmpty) { will always be false.

Upvotes: 1

Related Questions