typescript - Class-validator: odstrániť vlastnosť pri validácii na základe hodnoty inej vlastnosti
Používaním class-validator s NestJS to mám fungujúce takto:
export class MatchDeclineReason {
@IsString()
@IsEnum(MatchDeclineReasonType)
@ApiProperty()
type: MatchDeclineReasonType;
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@IsString()
@ApiProperty()
freeText: string;
}
takže ak delinceReason.type === Other, očakávam, že dostanem hodnotu reťazca freeText.
Avšak, ak je declineReason.type odlišný od Other, chcem, aby bola vlastnosť freeText odstránená.
Existuje nejaký spôsob, ako dosiahnuť takéto správanie bez písania CustomValidator?
Moja konfigurácia ValidationPipe:
app.useGlobalPipes(
new ValidationPipe({
disableErrorMessages: false,
whitelist: true,
transform: true,
}),
);
Odpoveď č. 1
Dá sa to dosiahnuť použitím vlastnej logiky na transformáciu hodnoty:
@ValidateIf(reason => reason.type === MatchDeclineReasonType.Other)
@Transform((params) =>
(params.obj.type === MatchDeclineReasonType.Other ? params.value : undefined)
)
@IsString()
@ApiProperty()
freeText: string;
