在Nestjs中使用类验证器验证嵌套对象



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

Profile的内容没有被验证。我遵循了文档的建议,但也许我只是遗漏了一些东西。

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

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; 
}

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

{
"first_name":"A",
"last_name":"B",
"profile":{
"gender":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},因为它是一个对象,而不是数组

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

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

所以我需要有:

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

最新更新