Search code examples
mongodbexpressexpress-validator

Express Validator .isLength and isEmail is not working


router.post("/", (req, res) => {
  body("name").isLength({ min: 3 }); // Validate name length
  body("email").isEmail(); // Validate email format
  body("password").isLength({ min: 8 }); // Validate password length

  const errors = validationResult(req); // Check for validation errors

  if (!errors.isEmpty()) {
    // Handle errors if present
    res.status(400).json({ errors: errors.array() });
  } else {
    // No errors, process request
    res.end("received"); // Currently just sends a message
    // Uncomment and customize below to actually create a user:
    // const user = User(req.body);
    // user.save();
    // res.send("User created successfully!");
  }
});

the code doesn't work as intended it doesn't give any error even if i give an empty req


Solution

  • Pass the validation middleware checks before the route handler callback as per the docs like so:

    router.post("/", 
        body("name").isLength({ min: 3 }),
        body("email").isEmail(),
        body("password").isLength({ min: 8 }),
        (req, res) => {
            const errors = validationResult(req); // Check for validation errors
        
            if (!errors.isEmpty()) {
                // Handle errors if present
                res.status(400).json({ errors: errors.array() });
            } else {
                // No errors, process request
                res.end("received"); // Currently just sends a message
                // Uncomment and customize below to actually create a user:
                // const user = User(req.body);
                // user.save();
                // res.send("User created successfully!");
            }
    });