0

Consider following Dtos:

export class Child {
  @ApiProperty({
    type: String,
    isArray: true,
  })
  name: string;

  @ApiProperty({
    type: Number,
    isArray: true,
  })
  age: number;
}

export class Parent {
  @ApiProperty({
    type: String,
    isArray: true,
  })
  name: string;

  @ApiProperty({
    type: [Child],
    isArray: true,
  })
  @ValidateNested({
    each: true,
    groups: ['ValidateChild'],
  })
  @IsNotEmpty({
    each: true,
    groups: ['ValidateChild'],
  })
  @IsArray({
    groups: ['ValidateChild'],
  })
  @Type(() => Child)
  campaignStrategies: Child[];
}

Then use validate() from class-validator to validate by group:

validate(parent, {groups: "ValidateChild"})

Finally, validate() response which mean parent.child is not exist when validate() is called:

{
    "undefined": "an unknown value was passed to the validate function"
}

The solution which I have found was:

const newParent = {
  ...parent,
  child: plainToInstance(Child, parent.child, {
    enableImplicitConversion: true,
  }),
};
validate(parent, {groups: "ValidateChild"});

Do we have another way to validate (By Group) the original parent object without use plainToInstance() for each nested fields?

1 Answer 1

0

You're encountering this error because @ValidateNested() only works when the nested objects (like Child) are actual class instances — not plain objects. This is a known behavior of class-validator.

validate() won't transform nested objects into class instances unless you explicitly do it yourself.

It's an open issue as well, you can see the related answer there.

You can solve it using plainToInstance() on the top-level object only, and @Type(() => Child) will handle nested transformation recursively (as long as it's used properly).

For example:

import { plainToInstance } from 'class-transformer';
import { validate } from 'class-validator';

const instance = plainToInstance(Parent, parent, {
  enableImplicitConversion: true,
});
validate(instance, { groups: ['ValidateChild'] });
  1. @Type(() => Child) tells class-transformer how to instantiate nested objects.

  2. plainToInstance(Parent, ...) will recursively apply it to campaignStrategies

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

Comments

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.