I'm trying to validate a date param (with class-validator) in my Nest.js api; below is what I have:
class DateValidate {
@IsDate()
date: Date;
}
@Get('day/:day')
getDayMealsPlan(@Param('day') day: DateValidate): any {
return day;
}
I'm passing the date param in the URL like so:
localhost:3000/meals/day/2022-03-06T11:00:00.000Z
It's throwing me a 400 error:
{
"statusCode": 400,
"message": [
"date must be a Date instance"
],
"error": "Bad Request"
}
I have a 2 part question:
- How to validate a date?
- How would a date look in the param? Is this the right way to do it: 2022-03-06T11:00:00.000Z
CodePudding user response:
I believe it should be:
@Get('day/:date') // <
getDayMealsPlan(@Param() o: DateValidate): any {
return o.date
}
CodePudding user response:
2022-03-06T11:00:00.000Z
this value is a String type. That's why class-validator is complaining not Date instance
.
You need to tell to transform your string format to Date.
You can achieve that using Type
decorator from class-transformer
.
class DateValidate {
@IsDate()
@Type(() => Date)
day: Date;
}
@Controller('something')
export class SomethingController {
@Get('day/:day')
getDayMealsPlan(@Param() params: DateValidate) {
console.log(params.day instanceof Date); // true
return params;
}
}