When using class-validator
in conjunction with NestJS, I have successfully implemented the following:
export class MatchDeclineReason {
@IsString()
@IsEnum(MatchDeclineReasonType)
@ApiProperty()
type: MatchDeclineReasonType;
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@IsString()
@ApiProperty()
freeText: string;
}
In this setup, if declineReason.type === Other
, I would like to receive a value for freeText
as a string.
Conversely, if declineReason.type
is anything other than Other
, I want the freeText
property to be removed completely.
My goal is to achieve this behavior without resorting to writing a CustomValidator
. Is there any way to do so?
This is how my ValidationPipe
is configured:
app.useGlobalPipes(
new ValidationPipe({
disableErrorMessages: false,
whitelist: true,
transform: true,
}),
);