Home > Net >  Nest.JS DTO Validation
Nest.JS DTO Validation

Time:03-30

My DTO is

 @Expose()
 @IsNotEmpty()
 @IsJSON({ each: true })
 filesRole: string

filesRole is something like that: [{"file": "14125.png", "role": "bg"}, {"file": "x12.png", "role": "cover"}]

I want to validate role to be bg or cover.

CodePudding user response:

You can try it with enum:

export enum Role {
  bg = 'bg',
  cover = 'cover',
}
@IsEnum(Role)
@Expose()
@IsNotEmpty()
@IsJSON({ each: true })
filesRole: Role

CodePudding user response:

update your main DTO:

@Expose()
@IsNotEmpty()
@IsArray()
@ValidateNested({ each: true })
filesRole: Data[]; 

Data DTO:

export class Data {
    @IsNotEmpty()
    @IsString()
    file: string;

    @IsNotEmpty()
    @IsString()
    @IsIn(Object.values(roleEnum))
    role: roleEnum;
}

roleEnum :

export enum roleEnum {
    bg = 'bg',
    cover = 'cover',
}
  • Related