javascriptnode.jsexpressexpress-validator

express-validator: Handling conditional validation


I have a form which takes the user email and password. I have setup validation with express validator which checks if the user email and password are empty and if email is a valid email as shown below.

const loginSchema = [
  body("email")
    .isEmail()
    .withMessage("email must contain a valid email address")
    .notEmpty()
    .withMessage("please enter email"),
  body("password").notEmpty().withMessage("please enter password"),
];

When testing in postman, if a user was to submit the form without entering email and password, it displays all error messages. How do I use conditionals with express validator to make it so that isEmail() withMessage is only called if the request body email is not empty?


Solution

  • From express-validator docs:

    If the option onlyFirstError is set to true, then only the first error for each field will be included.

    So you basically have to do this instead

    validationResult(req).array({ onlyFirstError: true })
    

    Alternatively, you can use the following to have the errors from a request be a map from field path to first error of that field:

    validationResult(req).mapped()