Search code examples
nestjsclass-validator

Nest class-validator minDate throws error even when the date is greater


I'm using Nest with class-validator and attempting to validate that the date provided by the UI is no earlier than today using @isDateString() and @MinDate()

export class SchemaDto {
    @IsOptional()
    @IsDateString()
    @MinDate(new Date())
    myDate?: Date;
}

The data I am sending in is a Date Objected with the following date:

    Mon Oct 04 2021 00:00:00 GMT-0400 (Eastern Daylight Time)

The error I am getting from class-validator is:

     minimal allowed date for myDate is Fri Oct 01 2021 15:57:18 GMT-0400 (Eastern Daylight Time) 

The problem:

If I remove the minDate decorator, everything works fine but I would rather validate this common case.

info: typescript: ~4.1.4

node: 12.4.0

class-validator: 0.13.1

nest: 7.0.0


Solution

  • To validate with @MinDate

    export class SchemaDto {
        @IsNotEmpty()
        @Transform( ({ value }) => new Date(value))
        @IsDate()
        @MinDate(new Date())
        myDate: Date;
    }
    

    But if value is optional, it might null or undefined, so:

    export class SchemaDto {
        @IsOptional()
        @Transform( ({ value }) => value && new Date(value))
        @IsDate()
        @MinDate(new Date())
        myDate?: Date;
    }