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

如何使用class-validator实现依赖其他变量的DTO条件验证?

依赖其他字段的DTO验证实现方案

针对你需要根据price_show的值约束price字段的需求,可以通过class-validator的条件验证装饰器组合实现:

import { IsBoolean, IsNumber, Min, ValidateIf, IsNil } from 'class-validator';

export class CreateItemDto {
    @IsBoolean()
    price_show: boolean;

    // 当price_show为true时,price必须是≥10的数字
    @ValidateIf(o => o.price_show === true)
    @IsNumber()
    @Min(10)
    // 当price_show为false时,price必须是null或者不传入该字段
    @ValidateIf(o => o.price_show === false)
    @IsNil()
    price: number | null;
}

关键逻辑说明:

  • @ValidateIf(o => o.price_show === true) + @IsNumber() + @Min(10):限定当price_show为true时,price必须是有效数字且最小值为10,不允许为null或未定义。
  • @ValidateIf(o => o.price_show === false) + @IsNil():限定当price_show为false时,price要么是null,要么完全不出现在请求体中(@IsNil()同时验证null和undefined两种情况)。

如果需要强制price_show为false时,请求体里绝对不能出现price字段,可以额外结合class-transformer的装饰器做转换处理:

import { IsBoolean, IsNumber, Min, ValidateIf, IsNil } from 'class-validator';
import { Transform } from 'class-transformer';

export class CreateItemDto {
    @IsBoolean()
    price_show: boolean;

    @ValidateIf(o => o.price_show === true)
    @IsNumber()
    @Min(10)
    @ValidateIf(o => o.price_show === false)
    @IsNil()
    @Transform(({ value, obj }) => obj.price_show ? value : undefined)
    price: number | null;
}

这里的@Transform会在请求体转换为DTO实例时,自动把price_show为false时的price字段设为undefined,配合@IsNil()完成严格验证。

内容的提问来源于stack exchange,提问作者jbundziow

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 23:52:39