【问题标题】:How to validate an array of Date with class validator?如何使用类验证器验证日期数组?
【发布时间】:2022-10-31 13:06:27
【问题描述】:

我要验证的发布请求正文中有一组日期:

{
    "meals": [...],
    "dates": [
        "2022-03-06T11:00:00.000Z",
        "2022-03-07T11:00:00.000Z"
    ]
}

这是我的 dto 课程:

export class CopyMealsPlanDto {
...// Another array

  @IsArray()
  @ValidateNested({ each: true })
  @IsDate()
  @Type(() => Date)
  dates: Date[];
}

但我收到了这个错误:

{
    "statusCode": 400,
    "message": [
        "dates must be a Date instance"
    ],
    "error": "Bad Request"
}

【问题讨论】:

    标签: api nestjs class-validator


    【解决方案1】:

    试试这个:

    export class CopyMealsPlanDto {
    ...// Another array
    
      @IsDateString({}, { each: true })
      dates: Date[];
    }

    您可以阅读有关如何验证数组 here 的更多信息。

    【讨论】:

      【解决方案2】:

      您可以使用 @IsDateString() 装饰器

      https://github.com/typestack/class-validator#validation-decorators

      【讨论】:

      • 嗨,如果我使用它,我会收到此错误:“日期必须是有效的 ISO 8601 日期字符串”
      • @webber 因为@IsDateString 检查 ISO8601 的日期类型。文档说:“@IsISO8601(). 的别名。”。在您的示例中,日期类型也是 ISO8601。可能您的数据包括不同的类型。
      猜你喜欢
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2020-05-07
      • 1970-01-01
      • 2021-03-09
      • 2020-07-30
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多