Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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,
    }),
  );
like image 870
Maoration Avatar asked Sep 13 '25 02:09

Maoration


1 Answers

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;
like image 143
intenser Avatar answered Sep 14 '25 16:09

intenser