Skip to content

fix: class-validator validate nested array of object by groups in NestJS #2612

@Sotatek-TuLe3

Description

@Sotatek-TuLe3

Description

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)
  childs: Child[];
}

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

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

Actual behavior

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

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

Expected behavior

The childs should be validated foreach element in array.

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions