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()

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()

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:

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! 🚀