[英]Class-validator: remove a property on validation, based on the value of another property
使用带有 NestJS class-validator
,我有这个工作:
export class MatchDeclineReason {
@IsString()
@IsEnum(MatchDeclineReasonType)
@ApiProperty()
type: MatchDeclineReasonType;
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@IsString()
@ApiProperty()
freeText: string;
}
所以如果delinceReason.type === Other
,我希望得到一个freeText
字符串值。
但是,如果declineReason.type
与Other
有任何不同,我希望将freeText
属性剥离。
有没有办法在不编写CustomValidator
的情况下实现这种行为?
我的ValidationPipe
配置:
app.useGlobalPipes(
new ValidationPipe({
disableErrorMessages: false,
whitelist: true,
transform: true,
}),
);
它可以通过使用自定义逻辑进行值转换来实现:
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@Transform((params) =>
(params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
)
@IsString()
@ApiProperty()
freeText: string;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.