Express-validator如何仅在存在另一个字段时才使字段成为必需字段

问题描述

express-validator,如何仅在存在另一个字段时才使该字段为必填字段?

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!'),];
};

仅在提供bank_code时,我想将字段account_number设置为必填字段,反之亦然

解决方法

6.1.0

版本express-validator添加了对条件验证器的支持。我目前在文档中没有看到它,但是有pull request带有更多信息。看来您应该能够按照以下方式定义验证:

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!'),];
};

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...