t97
t97

Reputation: 793

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

Upvotes: 3

Views: 2413

Answers (1)

Lars Flieger
Lars Flieger

Reputation: 2554

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;
}

Upvotes: 2

Related Questions