Express-validator 如何仅在存在另一个字段时才需要一个字段

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

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 of express-validator added support for conditional validators. I do not currently see it in the documentation but there is a 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!')
    ,
  ];
};

要添加到@Jason 的回答,这里是当对象在数组中并且您使用通配符语法时,如何根据另一个字段的值有条件地验证一个字段:

// only validate `target` if `requiresTarget` is true
body('people[*].weight')
  .if((value, { req, location, path }) => {

    /*
      Gets numeric, index value of "*". Adjust your regex as needed
      if nested data uses more than one wildcard
    */
    const wildcardIndex = parseInt(path.match(/([0-9]+)/)[1])

    // return a true value if you want the validation chain to proceed.
    // return false value if you want the remainder of the validation chain to be ignored
    return req.body.people[wildcardIndex].requiresWeight
  })
  .isFloat() // only applies this if `requiresWeight` is true
  .withMessage('weight must be float'),