Nest: Can't send date and validate that by IsDate validator

Created on 4 May 2018  路  3Comments  路  Source: nestjs/nest

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!

Most helpful comment

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 }));
    // ...
}

All 3 comments

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

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 }));
    // ...
}

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kiwikern picture kiwikern  路  3Comments

janckerchen picture janckerchen  路  3Comments

KamGor picture KamGor  路  3Comments

2233322 picture 2233322  路  3Comments

mishelashala picture mishelashala  路  3Comments