如何使用类验证器进行更高级的条件验证?

问题描述 投票:0回答:1

我对一个变量的验证要求取决于另一个变量的值。我不知道如何正确创建我的 DTO。

看我的例子:

export class CreateItemDto {
    @IsBoolean()
     price_show: boolean;
   
     @ValidateIf(o => o.price_show === true)
     @IsNumber()
     @Min(10)
     //TODO: if price_show is false, then price MUST BE NULL (or even should not be defined?). How to achieve that?
     price: number | null;
}
validation nestjs class-validator class-transformer
1个回答
0
投票

您可以使用

@Transform
装饰器将价格值设置为 null

...
import { Transform } from 'class-transformer';


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

  @Transform(({ value, obj }) => obj.price_show ? value : null)
  @ValidateIf((o) => o.price_show === true)
  @IsNumber()
  @Min(10)
  //TODO: if price_show is false, then price MUST BE NULL (or even should not be defined?). How to achieve that?
  price: number | null;
}

参考

© www.soinside.com 2019 - 2024. All rights reserved.