'How to validate an array of Date with class validator?

I have an array of dates in a post request body that I want to validate:

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

This is my dto class:

export class CopyMealsPlanDto {
...// Another array

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

But I'm getting this error:

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


Solution 1:[1]

You can use @IsDateString() decorator

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

Solution 2:[2]

Try this one:

export class CopyMealsPlanDto {
...// Another array

  @IsDateString({}, { each: true })
  dates: Date[];
}

You can read more about how to validate a array here.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DSabalsa
Solution 2 amirreza mousavi