nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.74k stars 7.63k forks source link

Can't send date and validate that by IsDate validator #631

Closed rafal-rudnicki closed 6 years ago

rafal-rudnicki commented 6 years ago

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x ] Documentation issue or request
[x ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

I'm wondering how to send date by POST method and validate that by @IsDate() decorator from class-validator library. I'm trying to achieve that by DTO class which looks this way:


export class ItemDto {
    @ApiModelProperty({ type: Date })
    @IsDate()
    readonly availableFrom;

    @ApiModelProperty({ type: Date })
    @IsDate()
    readonly availableTo;

    @ApiModelProperty({ type: String })
    @IsString()
    readonly idFromWebservice;

    @ApiModelProperty({ enum: ['allegro', 'olx'] })
    @IsString()
    readonly webservice;
}

but as a result i can't send date which has that format: "2018-05-23T18:25:43.511Z", because i have that error: "availableFrom must be a Date instance". Could someone send me an example how to do it right way? Thx!

kamilmysliwiec commented 6 years ago

Use @IsDateString() instead (see here https://github.com/typestack/class-validator)

ndraiman commented 5 years ago

You can use @Type decorator from class-transformer (docs)

Like this:

import { Type } from 'class-transformer';

export class ExampleDto {
    @IsDate()
    @Type(() => Date)
    someDate: Date
}

My controllers receive the properties as Date objects when the request was sent with ISO String


Just in case you're wondering, I'm applying the ValidationPipe like this:

import { ValidationPipe } from '@nestjs/common';

async function bootstrap() {
    // ...
    app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));
    // ...
}
lock[bot] commented 5 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.