0

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 
Karan Kumar
  • 2,678
  • 5
  • 29
  • 65
  • you can use interfaces in there but you'll need to pass some concrete class to `class-validator`. See: https://stackoverflow.com/a/53786899/5290447 – Micael Levi Oct 24 '21 at 14:42

1 Answers1

5

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[];
Karan Kumar
  • 2,678
  • 5
  • 29
  • 65