Skip to content
Advertisement

Validate array object – Swagger/NestJS

I am wondering if there’s a way to create a dto to validate array of object?

Example array:

[
  {
    "name": "Tag 1",
    "description": "This is the first tag"
  },
  {
    "name": "Tag 2",
    "description": "This is the second tag"
  }
]

At the moment I have this, while it works, it isn’t what I am after.

export class Tags {
  @ApiProperty({
    description: 'The name of the tag',
    example: 'Tag 1',
    required: true
  })
  @IsString()
  @MaxLength(30)
  @MinLength(1)
  name: string;

  @ApiProperty({
    description: 'The description of the tag',
    example: 'This is the first tag',
    required: true
  })
  @IsString()
  @MinLength(3)
  description: string;
}

export class CreateTagDto {
  @ApiProperty({ type: [Tags] })
  @Type(() => Tags)
  @ArrayMinSize(1)
  @ValidateNested({ each: true })
  tags: Tags[];
}

Advertisement

Answer

Just use ParseArrayPipe:

Update your Controller:

@Post()
createExample(@Body(new ParseArrayPipe({ items: Tags, whitelist: true })) body: Tags[]) {
  ...
}

Ensure to have items and whitelist set.

Update your DTO:

import { IsString, Length } from "class-validator";

export class Tags {
  @IsString()
  @Length(1, 30)
  name: string;

  @IsString()
  @Length(3)
  description: string;
}
User contributions licensed under: CC BY-SA
12 People found this is helpful
Advertisement