首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Nestjs中使用class-validator验证嵌套对象

在Nestjs中使用class-validator验证嵌套对象
EN

Stack Overflow用户
提问于 2021-01-18 21:10:54
回答 2查看 893关注 0票数 0

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

但是,配置文件的内容未经过验证。我遵循了文档上的建议,但也许我只是遗漏了一些东西。

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

代码语言:javascript
运行
复制
 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; 
}

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

代码语言:javascript
运行
复制
{
   "first_name":"A",
   "last_name":"B",
   "profile":{
      "gender":1
   }
}
EN

回答 2

Stack Overflow用户

发布于 2021-01-18 21:42:39

这将会有所帮助:

代码语言:javascript
运行
复制
export enum GenderType {
    Male = "male",
    Female = "female",
}

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

export class CreateClientDto {
    @IsObject()
    @ValidateNested()
    @Type(() => Profile)
    profile: Profile; 
}

附言:您不需要{each: true},因为它是一个对象,而不是一个数组

票数 1
EN

Stack Overflow用户

发布于 2021-01-18 23:21:52

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

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

所以我需要:

代码语言:javascript
运行
复制
export enum GenderType {
    Male = 'Male',
    Female = 'Female',
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65775173

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档