类验证器:根据另一个属性的值在验证时删除一个属性

Mao*_*ion 3 validation typescript class-validator nestjs

与 NestJS 一起使用class-validator,我的工作如下:

export class MatchDeclineReason {
  @IsString()
  @IsEnum(MatchDeclineReasonType)
  @ApiProperty()
  type: MatchDeclineReasonType;

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @IsString()
  @ApiProperty()
  freeText: string;
}
Run Code Online (Sandbox Code Playgroud)

所以如果delinceReason.type === Other,我希望得到一个freeText字符串值。


但是,如果 与declineReason.type有任何不同Other,我希望该freeText财产被剥夺。

有没有什么方法可以在不编写 的情况下实现这种行为CustomValidator

我的ValidationPipe配置:

  app.useGlobalPipes(
    new ValidationPipe({
      disableErrorMessages: false,
      whitelist: true,
      transform: true,
    }),
  );
Run Code Online (Sandbox Code Playgroud)

小智 6

可以通过使用自定义逻辑进行值转换来实现:

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @Transform((params) =>
    (params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
  )
  @IsString()
  @ApiProperty()
  freeText: string;
Run Code Online (Sandbox Code Playgroud)