【问题标题】:Validating objects with class validator使用类验证器验证对象
【发布时间】:2022-01-10 12:56:09
【问题描述】:

我正在尝试验证传递的对象是否属于某种类型。

国家对象

class Country {
 code : string;
 name: string;
}

验证码

  @IsNotEmpty()
  @IsNotEmptyObject()
  @IsObject()
  @ValidateNested()
  @Type(() => Country)
  country: Country;

@Type 是从 class-transformer 导入的

这是许多堆栈溢出问题中的答案。 例如:Class-validator - validate array of objects。它对我不起作用。这是针对单个对象而不是对象数组。

【问题讨论】:

    标签: node.js validation nestjs class-validator class-transformer


    【解决方案1】:

    试试这个:

    将以下内容添加到您的控制器:确保将whitelist: true 设置为true。 (这将删除不在 Country Schema 定义中的所有内容)

    @Post()
    createExample(@Body(new ValidationPipe({ whitelist: true })) body: ExampleDto) {
       ...
    }
    

    像这样添加你的 DTO

    class Country {
       @IsString()
       code : string;
    
       @IsString() // To make a field optional you can add @IsOptional
       name: string;
    }
    
    export class ExampleDto {
    
       // You do not require IsNotEmpty or because with IsString in Country you force it to be required.
       @ValidateNested()
       @Type(() => Country)
       country: Country;
    }
    

    【讨论】:

    • @Muljayan 这能回答你的问题吗?
    猜你喜欢
    • 2021-03-09
    • 2019-05-16
    • 2018-08-21
    • 2021-04-22
    • 2019-05-08
    • 1970-01-01
    • 2022-12-11
    • 2012-09-22
    相关资源
    最近更新 更多