NestJS中Class-validator如何根据另一属性值移除校验对象属性
解决方案
你全局已经开启了transform: true,可以直接用class-transformer提供的@Transform装饰器实现需求,无需编写自定义校验器,修改后的DTO代码如下:
import { Transform } from 'class-transformer'; import { IsString, IsEnum, ValidateIf } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; export class MatchDeclineReason { @IsString() @IsEnum(MatchDeclineReasonType) @ApiProperty() type: MatchDeclineReasonType; @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other) @IsString() @ApiProperty() @Transform(({ obj, value }) => { // 当type不为Other时直接移除freeText属性 if (obj.type !== MatchDeclineReasonType.Other) { delete obj.freeText; return undefined; } return value; }) freeText: string; }
逻辑说明
@Transform会在参数转换阶段自动执行,不需要额外配置- 当
type不等于Other时,直接从对象上删除freeText属性,符合你自动移除的要求 - 原有校验逻辑不受影响:
type为Other时仍然会校验freeText必须是合法字符串
如果你需要在用户非Other场景传入freeText时直接抛出校验错误而非静默过滤,可以使用条件校验方案:
export class MatchDeclineReason { @IsString() @IsEnum(MatchDeclineReasonType) @ApiProperty() type: MatchDeclineReasonType; @ValidateIf(reason => reason.type === MatchDeclineReasonType.Other) @IsString() @ValidateIf(reason => reason.type !== MatchDeclineReasonType.Other) @IsUndefined({ message: '非其他原因时不能传入freeText参数' }) @ApiProperty() freeText: string; }
内容的提问来源于stack exchange,提问作者Maor Barazani
相关产品推荐
相关产品推荐

