Reputation: 3176
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
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:
class ExperienceDto {
@IsEnum(Fields)
field: Fields;
@IsNumber()
years: number;
}
@ArrayNotEmpty()
@ArrayMinSize(1)
@ArrayMaxSize(3)
@ValidateNested({ each: true })
@Type(() => ExperienceDto) // imported from class-transformer package
experience: ExperienceDto[];
Upvotes: 6