繁体   English   中英

Class-validator:根据另一个属性的值在验证时删除一个属性

[英]Class-validator: remove a property on validation, based on the value of another property

使用带有 NestJS class-validator ,我有这个工作:

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

  @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
  @IsString()
  @ApiProperty()
  freeText: string;
}

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


但是,如果declineReason.typeOther有任何不同,我希望将freeText属性剥离。

有没有办法在不编写CustomValidator的情况下实现这种行为?

我的ValidationPipe配置:

  app.useGlobalPipes(
    new ValidationPipe({
      disableErrorMessages: false,
      whitelist: true,
      transform: true,
    }),
  );

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM