【问题标题】:Class-validator: remove a property on validation, based on the value of another propertyClass-validator:根据另一个属性的值在验证时删除一个属性
【发布时间】:2021-12-28 12:45:18
【问题描述】:

在 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,
    }),
  );

【问题讨论】:

    标签: typescript validation nestjs class-validator


    【解决方案1】:

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

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

    【讨论】:

    • 像魅力一样工作,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多