Open
Description
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?