Skip to content

question: How to validate nested array of object by groups in Nestjs with class-validator #2611

Open
@Sotatek-TuLe3

Description

@Sotatek-TuLe3

How to validate nested array of object by groups in Nestjs with class-validator

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: questionQuestions about the usage of the library.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions