Pooria Sadeghy
Pooria Sadeghy

Reputation: 443

Node express.js - express-validator: validationResult not working on middleware

I using express-validator plugin for validate my express.js project.

When i check validation in controller with validationResult method, everything is ok and validationResult return errors and validationResult.isEmpty() returns false.

But in middleware for same request validationResult.isEmpty() return true and there is no error there.

My index:

app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(validatorMiddleware)
app.use(router)

My middleware:

const validatorMiddleware = (req: Request, res: Response, next: NextFunction) => {
    const errors = validationResult(req)
    console.log(errors.isEmpty())
    if (errors.isEmpty()) {
        return next()
    }
    return res.status(422).json({
        errors: errors,
    })
}

My router:

const router = Router()
router.post('/register', registerRequest(), authController.register);
export default router

registerRequest method:

const registerRequest = () => [
    body('username').notEmpty().withMessage('Username is required'),
    body('email').isEmail().withMessage('Invalid email address'),
    body('password').isLength({ min: 6 }).withMessage('Password must be at least 6 characters long')
]

Upvotes: 0

Views: 79

Answers (1)

amirali
amirali

Reputation: 1

The problem you're experiencing is due to the placement of your validation middleware. In this order, the validatorMiddleware runs before the route-specific validations defined in registerRequest().

you could use it as a specific router middleware instead of global one. as below:

router.post('/register', registerRequest(), validatorMiddleware, authController.register);

Upvotes: 0

Related Questions