Search code examples
javascriptnode.jsexpressexpress-validator

Express-validator how to make a field required only when another field is present


express-validator, how do I make a field required only when another field exists?

const validateUpdateStore = () => {
  return [
    body('logo').optional().isURL().withMessage('invalid url'),
    body('email')
      .optional()
      .isEmail()
      .withMessage('email is invalid')
      .trim()
      .escape(),
    body('phone').optional().isInt().withMessage('integers only!'),
    body('account_number').optional().isInt().withMessage('integers only!'),
    body('bank_code').optional().isInt().withMessage('integers only!'),
  ];
};

I'd like to make the field bank_code required only when account_number is provided and vise-versa


Solution

  • Version 6.1.0 of express-validator added support for conditional validators. I do not currently see it in the documentation but there is a pull request with more information. It looks like you should be able to define your validation as follows:

    const validateUpdateStore = () => {
      return [
        body('logo').optional().isURL().withMessage('invalid url'),
        body('email')
          .optional()
          .isEmail()
          .withMessage('email is invalid')
          .trim()
          .escape(),
        body('phone').optional().isInt().withMessage('integers only!'),
        body('account_number')
          .if(body('bank_code').exists()) // if bank code provided
          .not().empty() // then account number is also required
          .isInt() // along with the rest of the validation
          .withMessage('integers only!')
        ,
        body('bank_code')
          .if(body('account_number').exists()) // if account number provided
          .not().empty() // then bank code is also required
          .isInt() // along with the rest of the validation
          .withMessage('integers only!')
        ,
      ];
    };