Home > Net >  Class-validator: remove a property on validation, based on the value of another property
Class-validator: remove a property on validation, based on the value of another property

Time:11-29

Using class-validator with NestJS, I have this working:

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

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

so that if the delinceReason.type === Other, I expect to get a freeText string value.


However, if the declineReason.type is any different from Other, I want the freeText property to be stripped away.

Is there any way to achieve this kind of behaviour without writing a CustomValidator?

My ValidationPipe configuration:

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

CodePudding user response:

It can be achieved by using a custom logic for value transformation:

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