0

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

2 Answers 2

7

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

this is what I have in my code. I have tried with {each:true} and without. Maybe I have an environment problem.
So let me ask it this way, what request are sending? What response are you receiving? What response do you expect to see? I still don't get what your problem is. Can you also post profile object in your code?
I have added sample payload. does class-validator not pick up enums ?
0

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',
}

2 Comments

What you did is correct, gender: GenderType is what it should be, not string!
Ooops! Now I know why this is happening! because enums are changed to number! unless you define an string for them! gender: 1 is actually Female! and gender: 0 is male cause its defined as the second element in your enum class! I edited my answer! check it again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.