5

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"
}

2 Answers 2

7

Try this one:

export class CopyMealsPlanDto {
...// Another array

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

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

Sign up to request clarification or add additional context in comments.

Comments

1

You can use @IsDateString() decorator

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

2 Comments

hi, if I use that, I'm getting this error: "dates must be a valid ISO 8601 date string"
@webber Because @IsDateString checking date type for ISO8601. Documentation says: "Alias for @IsISO8601().". In your example date type is also ISO8601. Probably your data includes different type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.