Karan Kumar
Karan Kumar

Reputation: 3176

NestJS class-validators on incoming requests using interface

I need to use an interface through class-validator to validate the incoming form for a specific field in the incoming request body.

The interface:

export enum Fields {
  Full_Stack_Dev = 'full stack dev',
  Frontend_Dev = 'frontend dev',
  Backend_Dev = 'backend dev',
}

export interface Experience {
  field: Fields;
  years: number;
}

And here is the DTO Class:

@IsEnum(Languages)
  languages: Languages[];

  experience: Experience[]; // 👈 Not sure which decorator to use for interfaces 

Upvotes: 0

Views: 5455

Answers (1)

Karan Kumar
Karan Kumar

Reputation: 3176

Okay after doing a lot of research, I found a workaound for this:

First of all, Interfaces CANNOT be used directly. Officially declared by class-validators issue here

This is what I did:

  1. Changed the interface into a separate class and added validation on its properties
class ExperienceDto {
  @IsEnum(Fields)
  field: Fields;
  @IsNumber()
  years: number;
}
  1. Then used this class as type to validate Array of Objects in the ACTUAL DTO CLASS (not the above one)
  @ArrayNotEmpty()
  @ArrayMinSize(1)
  @ArrayMaxSize(3)
  @ValidateNested({ each: true })
  @Type(() => ExperienceDto) // imported from class-transformer package
  experience: ExperienceDto[];

Upvotes: 6

Related Questions