← Back
class-validator nestjs

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:

🖖