express-validator returns validation errors twice
I don't know why when req.body
is a empty object - {}
, the validator will run through all node of validation chain. You can check again, add each message for each condition, like as follow:
class UserRequestValidator extends RequestValidator { public createUser = [ body('username') .isString().withMessage('username must be a string') // you can see both error messages in the response .exists().withMessage('username must be exist'), body('password') // the same for this field .isString() .exists(), this.validate, ]; public fetchUserById = [ param('id') // because id is exist in `req.params`, then only one test has been executed. .isString().withMessage('id must be a string') .isUUID() .exists(), this.validate, ];}
I found a solution for your case in https://github.com/express-validator/express-validator/issues/638 , stop chain in the first error with .bail()
function.
Then your validator class will be like:
class UserRequestValidator extends RequestValidator { public createUser = [ body('username') // always check exists() first .exists().withMessage('username must be exist').bail() .isString().withMessage('username must be a string').bail(), body('password') .exists().bail() .isString().bail(), this.validate, ]; public fetchUserById = [ param('id') .isString() .isUUID() .exists(), this.validate, ];}
You can also set onlyFirstError
to true
when retrieving the error array.From the documentation:
If the option onlyFirstError is set to true, then only the first errorfor each field will be included
Example usage:
function validateRequestParams (req, res, next) { const errors = validationResult(req) if (errors.isEmpty()) { return next() } else { return res.status(400).json({ bodyValidationErrors: errors.array({ onlyFirstError: true }) }) }}