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,
}),
);
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With