#Unable to validate DTO attribute with IsISO8601

12 messages · Page 1 of 1 (latest)

brave imp
brave imp
final raptor
#

@IsISO8601(options?: IsISO8601Options)

Checks if the string is a valid ISO 8601 date.
If given value is not a string, then it returns false.
Use the option strict = true for additional checks for a valid date, e.g. invalidates dates like 2019-02-29.

brave imp
#

It does not matter. The problem is how NestJS works:

  1. First it transforms the incoming HTTP string into a Date object.
  2. Then, the result from that Date object is validated as ISO8601 (which obviously will always result in falsy).

I was hoping for some workound as we want to accept ISO8601 dates only.

#

I guess we will stay with

@Type(() => Date)
@IsDate()
date: Date

😦

#

There should be something like this in class-validator:

@Type(() => Date)
@IsDate({ acceptFormat: ['iso8601'] })
date: Date
final raptor
#
import { IsISO8601 } from 'class-validator';

export class DateDto {
  @IsISO8601({ strict: true })
  date: Date;
}

I just tried that and it works perfectly, throws error on IETF-compliant RFC 2822 timestamps:

"Mon, 03 Jun 2023 09:30:00 +0000"
"Tue, 04 Jun 2023 14:45:30 -0400"
"Wed, 05 Jun 2023 20:15:10 +0800"
"Thu, 06 Jun 2023 03:22:45 -0700"
brave imp
#

Are you sure your date: Date is really a Date type without @Type(() => Date) ?

#

I am having:

date.getTime is not a function

subtle magnet
#

The order of transformation and then validation is kind of unfortunate, but there's no other way, class validator only works on classes, so it must be first transformed into a class. This causes problems like you describe. The "solution" is to create custom transform functions which also do the validation in the same step and skip the class-validator decorator.