5

我有 TypeScript NestJS 项目。

我需要验证传入的 DTO 到我的 API。它可以被描述为“创建项目”,其中我们有建筑类型(房屋、公寓、花园),并且根据我们需要定义的类型:

  • 房子:楼层,包括房间
  • 公寓:房间
  • 花园:什么都没有(它是一个“房间”)

房屋类型示例:

{
  type: HOUSE,
  floors: [
    {
      name: "1st floor",
      rooms: [
        {
          name: "bedroom"
        }
      ]
    }
  ]
}

扁平型示例:

{
  type: FLAT,
  rooms: [
    {
      name: "bedroom"
    }
  ]
}

我过去AJVclass-validator.

我的问题是,如果我可以在class-validator

4

2 回答 2

0

您必须为此创建一个自定义验证器。文档非常好: https ://github.com/typestack/class-validator#custom-validation-classes

当您创建自定义验证器类时,在您的实现中,validate您可以访问在参数中验证的其他参数args。只需编写您的 if 语句,如果不满足则返回 false。您甚至可以返回自定义错误消息并实现自己的装饰器。

于 2021-12-21T05:33:15.843 回答
0

With class-validator you have the options of Conditional Validation and of Group Validation, or you could always create a custom pipe and use AJV as you are used to. For the conditional validation you could create validations based on type and then let class-validator take care of the rest

于 2020-02-14T16:30:32.197 回答