2

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?

1
  • Dont forget ` @Type(()=>LineDto)` on the arrary field Commented Oct 12, 2023 at 12:51

1 Answer 1

7

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[];
}
Sign up to request clarification or add additional context in comments.

3 Comments

It should be emphasized that the @Type line is important else the validation wont take place
cant this be done without creating a new type for hosting array, what if i just wanted to use CreateBetInput[] at controller level?
@DeekshithAnand as we get body data from the controller's parameters and they usually are in JSON objects with the format of {...data} and best practices say not to use array formats for the top level of the body objects like [...data] so this is a right pattern.

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.