繁体   English   中英

如何做条件检查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-validator v5.xx 尚未提供条件验证支持,但即将推出
以下是Pull Request,如果您想提供有关API的反馈: https//github.com/express-validator/express-validator/pull/658

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

可以继续使用它v5.xx就像你在v3.xx 我们不建议这样做,因为它已被弃用,并且可能在v6到期时被删除(尚未!)。

所有文档都在这里 ,与更新的API文档并排。

免责声明:我是快速验证者维护者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM