🚀 Documentation crafted by Sonicar Tech LLC — get your own docs shipped in 1 week →
Class Validator Documentation by Sonicar.Tech
Validation

Validating Nested Objects

Use @ValidateNested() to validate nested class instances, arrays of nested objects, and deeply nested object graphs.

Basic Nested Validation

If your object contains nested objects and you want the validator to perform their validation too, then you need to use the @ValidateNested() decorator:

import { ValidateNested } from 'class-validator';

export class Post {
    @ValidateNested()
    user: User;
}

Array of Nested Objects

It also works with arrays of nested objects:

import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

export class Post {
    @ValidateNested({ each: true })
    @Type(() => User)
    users: User[];
}

Deep Nested Objects

You can validate deeply nested objects:

import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';

export class Profile {
    @IsString()
    name: string;
}

export class User {
    @ValidateNested()
    @Type(() => Profile)
    profile: Profile;
}

export class Post {
    @ValidateNested()
    @Type(() => User)
    user: User;
}

The nested object must be an instance of a class, otherwise @ValidateNested won't know what to validate against.

🚀 Need documentation like this for your own product?

This site was built by Sonicar Tech LLC — we help SaaS, B2B, Enterprise, FinTech, and AI companies launch professional, docs-as-code documentation 60% faster and cheaper, with first drafts delivered in 1 week.

Visit sonicar.tech →

On this page