如何做条件检查 express-validator 5.3.0?

How to do conditional check express-validator 5.3.0?

export function valUPM() {
  return (req: Request, _res: Response, next: NextFunction) => {
    req
      .checkBody(
        "paymentType",
        `paymentType: ${messages.getFromSession(req, "mustNotBeEmpty")}`
      )
      .notEmpty();
    if (req.body.paymentType === "USP") {
      req
        .checkBody(
          "storeId",
          `storeId: ${messages.getFromSession(req, "mustNotBeEmpty")}`
        )
        .notEmpty();
    } else if (req.body.paymentType === "CC") {
      if (req.body.register) {
        req
          .checkBody(
            "register",
            `register: ${messages.getFromSession(req, "mustBeBoolean")}`
          )
          .isBoolean();
      } else {
        req
          .checkBody(
            "register",
            `register: ${messages.getFromSession(req, "mustNotBeEmpty")}`
          )
          .notEmpty();
      }
    }
    req.getValidationResult().then(errs => {
      if (errs.isEmpty()) {
        return next();
      }
      const error = new BFFError(
        400,
        "BadRequest",
        1,
        errs.array().map(error => {
          return { [error.param]: error.msg };
        })
      );
      return next(Error(JSON.stringify(error)));
    });
  };
}

更改为 API 后如何在快速验证器中实现此类逻辑

在 if 循环中调用 req.checkBody 或所需的验证函数可以实现如上所示的技巧,但在 API 中更改后如何实现 我尝试了一种变通方法,将 paymentTYpe 检查为自定义验证器并实施检查并将消息放入自定义验证器,但密钥发生了变化。

使用当前的 APi 执行此操作的正确方法是什么,因为这对所有想要从 3.0.0 更新到最新的 express-validator API

express-validatorv5.x.x不支持条件验证,但很快
这是 Pull Request,如果您想就 API 提供反馈:https://github.com/express-validator/express-validator/pull/658

但是,请注意旧版 API(使用 req.checkBody()req.getValidationResult() 等的遗留版本尚未从 express-validator 中删除。

可以v5.x.x中继续使用它,就像在v3.x.x中一样。只是不建议这样做,因为它已被弃用并且可能会在 v6 到期时被删除(还没有!)。

所有文档都是 here,与较新的 APIs 文档并排。

免责声明:我是 express-validator 维护者。