【问题标题】:Validating nested objects using class-validator in Nestjs在 Nestjs 中使用类验证器验证嵌套对象
【发布时间】:2021-04-22 18:56:30
【问题描述】:

我在验证嵌套对象时遇到了困难。使用类验证器运行 nestJs。顶级字段(first_name、last_name 等)验证正常。 Profile 对象在顶层被验证 OK,即如果我作为数组提交,我会得到正确的错误,它应该是一个对象。

然而,个人资料的内容并未得到验证。我遵循了文档上的建议,但也许我只是遗漏了一些东西。

有人知道如何验证嵌套对象字段吗?

 export enum GenderType {
    Male,
    Female,
}

export class Profile {
    @IsEnum(GenderType) gender: string;
}

export class CreateClientDto {
    @Length(1) first_name: string;

    @Length(1) last_name: string;

    @IsEmail() email: string;

    @IsObject()
    @ValidateNested({each: true})
    @Type(() => Profile)
    profile: Profile; 
}

当我发送此有效负载时,我预计它会失败,因为性别不在枚举或字符串中。但它并没有失败

{
   "first_name":"A",
   "last_name":"B",
   "profile":{
      "gender":1
   }
}

【问题讨论】:

    标签: nestjs class-validator


    【解决方案1】:

    这会有所帮助:

    export enum GenderType {
        Male = "male",
        Female = "female",
    }
    
    export class Profile {
        @IsEnum(GenderType) 
        gender: GenderType;
    }
    
    export class CreateClientDto {
        @IsObject()
        @ValidateNested()
        @Type(() => Profile)
        profile: Profile; 
    }
    
    

    P.S:你不需要{each: true},因为它是一个对象而不是一个数组

    【讨论】:

    • 这就是我的代码中的内容。我试过 {each:true} 和没有。也许我有环境问题。
    • 那么让我这样问,发送的是什么请求?你收到什么回应?您希望看到什么回应?我还是不明白你的问题是什么。您还可以在代码中发布配置文件对象吗?
    • 我添加了示例有效负载。类验证器不选择枚举吗?
    【解决方案2】:

    https://www.typescriptlang.org/docs/handbook/enums.html#string-enums

    TS 文档说要初始化字符串枚举。

    所以我需要:

    export enum GenderType {
        Male = 'Male',
        Female = 'Female',
    }
    

    【讨论】:

    • 你做的是对的,gender: GenderType是应该的,不是字符串!
    • 糟糕!现在我知道为什么会这样了!因为枚举改为数字!除非你为他们定义一个字符串! gender: 1其实是女的! gender: 0 是男性,因为它被定义为枚举类中的第二个元素!我编辑了我的答案!再检查一遍!
    猜你喜欢
    • 2019-05-16
    • 2021-03-09
    • 2021-05-05
    • 2019-05-08
    • 2020-06-05
    • 2012-09-22
    • 2022-08-02
    • 2020-12-02
    相关资源
    最近更新 更多