'Nest.JS DTO Validation

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.



Solution 1:[1]

You can try it with enum:

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

Solution 2:[2]

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',
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 water_ak47
Solution 2 prashant isotiya