class-validator icon indicating copy to clipboard operation
class-validator copied to clipboard

question: Dynamic Validation. How?

Open ArtiomOganesyan opened this issue 3 years ago • 1 comments

I was trying to: Make a DTO class. Which consists of three fields. Type an enum, title an object, text an object. If type is enum1 than I need to validate title and text. If type is enum2 than only text, however there must be no title in DTO, whitelist is true.

{
  type: 'enum1',
  title: {
    en: 'en',
  },
  text: {
    en: 'en',
  },
}
{
  type: 'enum2',
  text: {
    en: 'en',
  },
}

The problem: Don't understand how to achieve this behavior. I tried to use ValidateIf, however it doesn't really my case.
All it does is if type enum2 than title can be anything. Any ideas regarding such or similar construction will be helpful.

export class ContentBlocksDTO {
  @ApiProperty({ required: true, enum: ContentBlockTypes })
  @IsEnum(ContentBlockTypes)
  type!: ContentBlockTypes;

  @ApiProperty({ required: true, type: TranslatableDto })
  @ValidateIf(
    (dto: ContentBlocksDTO) => dto.type === ContentBlockTypes.Spoiler,
   )
  @IsDefined()
  @ValidateNested()
  @Type(() => TranslatableDto)
  title!: TranslatableDto;

  @ApiProperty({ required: true, type: TranslatableDto })
  @IsDefined()
  @ValidateNested()
  @Type(() => TranslatableDto)
  text!: TranslatableDto;
}

ArtiomOganesyan avatar Nov 25 '21 14:11 ArtiomOganesyan

Also interested about how to solve this correctly

aralroca avatar May 02 '23 10:05 aralroca