admin管理员组

文章数量:1318336

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?

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?

Share Improve this question edited Dec 15, 2021 at 22:42 Heartbit 1,8362 gold badges16 silver badges29 bronze badges asked Dec 15, 2021 at 22:25 João NorbertoJoão Norberto 231 silver badge5 bronze badges 1
  • Dont forget ` @Type(()=>LineDto)` on the arrary field – Gilbert Commented Oct 12, 2023 at 12:51
Add a ment  | 

1 Answer 1

Reset to default 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[];
}

本文标签: javascriptValidate an array of objects with classvalidator and NestjsStack Overflow