Reputation: 788
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
}
}
Upvotes: 0
Views: 12688
Reputation: 1549
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
Upvotes: 7
Reputation: 788
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',
}
Upvotes: 0