@MaxDate from class-validator not working as expected with Nestjs

Viewed 979

I don't have a lot of experience developing with Nodejs/Nestjs. I'm developing a REST API where one of endpoints receives a User body with a birthday property.

I want to validate that date of birth is always before the current day. This is a snippet of my code:

import { IsString, IsDateString, MaxDate } from 'class-validator';

export class CreateUserDto {
  @IsString()
  readonly username: string;

  @IsDateString()
  @MaxDate(new Date())
  readonly dateofbirth: Date;
}

And this is my entity:

import { Entity, Column, PrimaryColumn } from 'typeorm';

@Entity()
export class User {
  @PrimaryColumn()
  username: string;

  @Column()
  dateofbirth: Date;
}

However, when making a POST request I always get the same error and can't understand why: {"statusCode":400,"message":["maximal allowed date for dateofbirth is Mon Nov 01 2021 12:20:11 GMT+0000 (Western European Standard Time)"],"error":"Bad Request"}

Thank you for your help and time.

2 Answers

I solved the problem when added @Type(() => Date) to dateofbirth from class-transformer

The date passed into the Validator MaxDate is stored once when the service is started. So MaxDate is now comparing the date when the service started with the given date.

I did not find a solution to use the MaxDate Decorator with the current time. At the end we compare the sent date with current time in the controller function (the old/classic way).

Related