I am using class-validator with NestJS and trying to validate an array of objects, with this layout:
[
{gameId: 1, numbers: [1, 2, 3, 5, 6]},
{gameId: 2, numbers: [5, 6, 3, 5, 8]}
]
My resolver
createBet(@Args('createBetInput') createBetInput: CreateBetInput) {
return this.betsService.create(createBetInput);
}
My createBetInput DTO
import { InputType, Field, Int } from '@nestjs/graphql';
import { IsArray, IsNumber } from 'class-validator';
@InputType()
export class CreateBetInput {
@IsNumber()
@Field(() => Int)
gameId: number;
@Field(() => [Int])
@IsArray()
numbers: number[];
}
I've tried some solutions but I haven't been successful, honestly, I have no idea how to do this.
How can I modify the DTO to get the necessary validation?
CodePudding user response:
There are options of class-validator
mixed with class-transformer
to validating nested objects, your Array also is a nested object, so you can validate that like this:
import { Type } from 'class-transformer';
import { IsArray, ValidateNested } from 'class-validator';
class ItemsOfBet {
@IsArray()
@ValidateNested({ each: true })
@Type(() => CreateBetInput)
items: CreateBetInput[];
}