class-validator與 NestJS 一起使用,我有這個作業:
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,
}),
);
uj5u.com熱心網友回復:
可以通過使用自定義邏輯進行值轉換來實作:
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@Transform((params) =>
(params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
)
@IsString()
@ApiProperty()
freeText: string;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/368820.html
