IsDate VS IsDateString and interoperability {class-validator.js} {nestjs}
In class-validator, @IsDate() and @IsDateString() serve different purposes when validating date-related fields. Here's a breakdown of the differences:
1. @IsDate()
- Validates whether the value is an instance of
Date. - Typically used when the property is expected to hold a JavaScript
Dateobject. - It does not work with string-based dates; the value must be explicitly converted to a
Dateobject before validation.
Example:
import { IsDate } from 'class-validator';
class MyDto {
@IsDate()
dateField: Date;
}
const dto = new MyDto();
dto.dateField = new Date(); // ✅ Valid
dto.dateField = '2024-03-06'; // ❌ Invalid (string is not a Date object)
If you receive a date as a string (e.g., from a JSON payload), you need to transform it into a Date object using tools like class-transformer before validation.
2. @IsDateString()
- Validates whether the value is an ISO 8601 date string.
- It checks if the string is a valid date representation (
YYYY-MM-DD,YYYY-MM-DDTHH:mm:ss.sssZ, etc.). - It does not convert the value into a
Dateobject.
Example:
import { IsDateString } from 'class-validator';
class MyDto {
@IsDateString()
dateField: string;
}
const dto = new MyDto();
dto.dateField = '2024-03-06T15:00:00.000Z'; // ✅ Valid (ISO 8601 format)
dto.dateField = '2024-03-06'; // ✅ Valid (YYYY-MM-DD format)
dto.dateField = new Date(); // ❌ Invalid (not a string)
dto.dateField = '06-03-2024'; // ❌ Invalid (not ISO format)
When to Use Which?
| Decorator | Expected Input | When to Use |
|---|---|---|
@IsDate() |
JavaScript Date object |
When working with actual Date instances in the backend. |
@IsDateString() |
ISO 8601 formatted string | When receiving date values as strings in a request payload and ensuring they are correctly formatted. |
Additional Considerations:
-
If you're using NestJS with DTOs, the incoming request body is typically JSON, meaning all date values are initially strings. Therefore, you might prefer
@IsDateString()unless you convert them toDateobjects usingclass-transformer's@Type(() => Date). -
Example using
class-transformerwith@IsDate():import { IsDate } from 'class-validator'; import { Type } from 'class-transformer'; class MyDto { @Type(() => Date) // Converts string to Date object before validation @IsDate() dateField: Date; }
This ensures that a string date from a JSON request gets converted into a Date object before validation.
Let me know if you need more clarification! 🚀