Validating array of items in nestjs
Nestjs uses class-validator to validate the body of an http request.
Despite the documentation, to validate elements inside an array you need both @ValidateNested annotation (with each option to be true) and @Type annotation from class-transformer
This is a real world usage:
import { Type } from "class-transformer";
import { IsNotEmpty, IsOptional, ValidateNested } from "class-validator";
/**
* Body of the PATCH request to update Post tags
*/
export class UpdatePostTagsRequest {
@IsNotEmpty()
postId: string;
@ValidateNested({ each: true })
@Type(() => Tag)
seats: Tag[];
}
class Tag {
@IsNotEmpty()
public id: string;
@IsNotEmpty()
public label: string;
}
By the way, multi-dimensional arrays are not supported by this library.
Sources:
- https://stackoverflow.com/questions/58343262/class-validator-validate-array-of-objects/58366367#58366367
- https://github.com/typestack/class-validator/issues/374
- https://github.com/typestack/class-validator/issues/479
🖖