I have a DTO that looks like this:
class PersonDto {
readonly name: string;
readonly birthDate: Date;
}
My NestJs controller method looks like this:
@Post
create(@Body() person: PersonDto) {
console.log("New person with the following data:", person);
// more logic here
}
The JSON data that gets posted has birthDate
as a string: "2020-01-15"
. How can I convert this string to a JavaScript Date
object? I'd like to add the @IsDate
class-validation to PersonDto
but currently that would fail.
I figured out how to use the global ValidationPipe
with a Date property and the @IsDate()
annotation:
The first step is to allow transformations like this (my bootstrap file as an example):
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({transform: true}));
await app.listen(3000);
}
bootstrap();
Then you need to annotate the DTO with the @Type()
annotation:
import { IsDate } from 'class-validator';
import { Type } from 'class-transformer';
class PersonDto {
readonly name: string;
@Type(() => Date)
@IsDate()
readonly birthDate: Date;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With