Nested DTO validation helps check data inside objects within objects. It makes sure all parts of your data are correct before using them.
Nested DTO validation in NestJS
import { Type } from 'class-transformer'; import { ValidateNested, IsString } from 'class-validator'; class ChildDTO { @IsString() name: string; } class ParentDTO { @ValidateNested() @Type(() => ChildDTO) child: ChildDTO; }
Use @ValidateNested() to tell NestJS to validate the nested object.
Use @Type(() => ChildDTO) from class-transformer to help NestJS know the nested object type.
import { IsString, ValidateNested } from 'class-validator'; import { Type } from 'class-transformer'; class AddressDTO { @IsString() street: string; @IsString() city: string; } class UserDTO { @IsString() name: string; @ValidateNested() @Type(() => AddressDTO) address: AddressDTO; }
import { IsString, ValidateNested } from 'class-validator'; import { Type } from 'class-transformer'; class ItemDTO { @IsString() title: string; } class OrderDTO { @ValidateNested({ each: true }) @Type(() => ItemDTO) items: ItemDTO[]; }
This NestJS controller accepts a POST request to create a user. The user data includes a nested profile object. Both username and profile.bio are validated as strings.
import { Controller, Post, Body } from '@nestjs/common'; import { IsString, ValidateNested } from 'class-validator'; import { Type } from 'class-transformer'; class ProfileDTO { @IsString() bio: string; } class CreateUserDTO { @IsString() username: string; @ValidateNested() @Type(() => ProfileDTO) profile: ProfileDTO; } @Controller('users') export class UsersController { @Post() createUser(@Body() createUserDto: CreateUserDTO) { return `User ${createUserDto.username} with bio '${createUserDto.profile.bio}' created.`; } }
Always use @Type(() => NestedDTO) with @ValidateNested() for nested validation to work.
If you forget @Type(), nested validation will not run correctly.
For arrays of nested objects, add { each: true } option to @ValidateNested().
Nested DTO validation checks data inside objects within objects automatically.
Use @ValidateNested() and @Type() together for nested validation.
This keeps your data safe and your code clean by reusing validation rules.