How to validate dependent fields in NestJS DTO (based on enum value)

12 hours ago 1
ARTICLE AD BOX

I’m working on defining a DTO for a POST endpoint in a NestJS application. My current DTO looks something like this:

export class DraftCreation { entityType: EntityType; formData: TypeA | TypeB | TypeC; entityId: string; }

where entityType is an enum..

Problem

I want to validate dependent fields at runtime, specifically:

formData should be validated based on the value of entityType

For example:

If entityType = PJD, then formData should match TypeA

If entityType = SHEET_ELEMENT, then formData should match TypeB

etc.

If the formData does not match the expected type, the request should fail validation (e.g., in Swagger or via class-validator)

Question

What is the best practice to handle this in NestJS?

Should I use custom class-validator decorators for conditional validation?

Is there a better pattern (e.g., discriminated unions, pipes, or separate DTOs)?

How can I ensure proper validation and Swagger documentation support for this use case?

Additional Context

I want validation to happen automatically when a request is made (via DTO validation), not manually inside the service layer.

Read Entire Article