I am wondering if there’s a way to create a dto to validate array of object?
Example array:
JavaScript
x
11
11
1
[
2
{
3
"name": "Tag 1",
4
"description": "This is the first tag"
5
},
6
{
7
"name": "Tag 2",
8
"description": "This is the second tag"
9
}
10
]
11
At the moment I have this, while it works, it isn’t what I am after.
JavaScript
1
29
29
1
export class Tags {
2
@ApiProperty({
3
description: 'The name of the tag',
4
example: 'Tag 1',
5
required: true
6
})
7
@IsString()
8
@MaxLength(30)
9
@MinLength(1)
10
name: string;
11
12
@ApiProperty({
13
description: 'The description of the tag',
14
example: 'This is the first tag',
15
required: true
16
})
17
@IsString()
18
@MinLength(3)
19
description: string;
20
}
21
22
export class CreateTagDto {
23
@ApiProperty({ type: [Tags] })
24
@Type(() => Tags)
25
@ArrayMinSize(1)
26
@ValidateNested({ each: true })
27
tags: Tags[];
28
}
29
Advertisement
Answer
Just use ParseArrayPipe:
Update your Controller:
JavaScript
1
5
1
@Post()
2
createExample(@Body(new ParseArrayPipe({ items: Tags, whitelist: true })) body: Tags[]) {
3
4
}
5
Ensure to have items
and whitelist
set.
Update your DTO:
JavaScript
1
12
12
1
import { IsString, Length } from "class-validator";
2
3
export class Tags {
4
@IsString()
5
@Length(1, 30)
6
name: string;
7
8
@IsString()
9
@Length(3)
10
description: string;
11
}
12