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;