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
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: