You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 12:24:04