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

Dam*_*ndy 11 javascript node.js express 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!'),
  ];
};
Run Code Online (Sandbox Code Playgroud)

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

Jas*_*man 15

Express -validator 6.1.0版本添加了对条件验证器的支持。我目前在文档中没有看到它,但有一个包含更多信息的拉取请求。看起来您应该能够按如下方式定义验证:

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!')
    ,
  ];
};
Run Code Online (Sandbox Code Playgroud)