Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  63] [ 1]  / answers: 1 / hits: 20295  / 4 Years ago, sat, february 15, 2020, 12:00:00

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.


More From » json

 Answers
5

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

[#51207] Saturday, February 8, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
braeden

Total Points: 231
Total Questions: 96
Total Answers: 86

Location: Somalia
Member since Mon, Dec 28, 2020
3 Years ago
;