如何使用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
相关产品推荐
相关产品推荐

