简体   繁体   中英

Validating nested objects using class-validator in Nestjs

I am having difficulty with validating a nested object. Running nestJs using class-validator. The top level fields (first_name, last_name etc) validate OK. The Profile object is validated OK at the top level, ie if I submit as an array I get back the correct error that it should be an object.

The contents of Profile however are not being validated. I have followed suggestions on the docs but maybe I am just missing something.

Does anyone know how to validate nested object fields?

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

When I send this payload I expect it to fail because gender is not in the enum or a string. But it is not failing

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

This will help:

export enum GenderType {
    Male = "male",
    Female = "female",
}

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

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

PS: You don't need {each: true} because it's an object not an array

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

TS docs say to initialize the string enum.

So I needed to have:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM