NestJS course ยท Module 10: Data Validation

Nested Validation - Deep Inspection

3 min read ยท
In this lesson5

So far, we've been validating simple, flat objects. But what if incoming data has nested objects or arrays of objects? We need deep inspection - the guards must check not only the person at the gate, but also their luggage, documents in the bag, and items in the pockets.

The Problem - Flat Validation Is Not Enough

Imagine a DTO for a legion that contains a list of legionaries:

// WITHOUT nested validation
export class CreateLegioDto {
  @IsString()
  name: string;

  @IsArray()
  soldiers: CreateSoldierDto[];  // Array of objects
  // But is each object in the array valid? WE DON'T KNOW!
}

@IsArray() alone only checks whether the value is an array - it won't validate the contents of the objects inside!

@ValidateNested() - the nested object guard

The @ValidateNested() decorator tells class-validator: "Also validate the inner object":

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

class CreateSoldierDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsNumber()
  @Min(16)
  age: number;
}

export class CreateLegioDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @ValidateNested()
  @Type(() => CreateSoldierDto)
  commander: CreateSoldierDto;
}

Important: @ValidateNested() always requires @Type() from class-transformer! Without it, NestJS doesn't know which class to convert the raw object to.

Validating Arrays of Nested Objects

When you have an array of objects, you must add { each: true }:

export class CreateLegioDto {
  @IsString()
  name: string;

  @ValidateNested({ each: true })
  @Type(() => CreateSoldierDto)
  soldiers: CreateSoldierDto[];
}

The { each: true } parameter tells the decorator to check each element of the array separately. Without it, nested validation won't work on arrays.

Multi-Level Nesting

Nesting can go many levels deep:

class WeaponDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsNumber()
  @Min(1)
  damage: number;
}

class SoldierDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @ValidateNested()
  @Type(() => WeaponDto)
  primaryWeapon: WeaponDto;

  @IsOptional()
  @ValidateNested()
  @Type(() => WeaponDto)
  secondaryWeapon?: WeaponDto;
}

class CohortDto {
  @IsString()
  name: string;

  @ValidateNested({ each: true })
  @Type(() => SoldierDto)
  soldiers: SoldierDto[];
}

export class CreateLegioDto {
  @IsString()
  name: string;

  @ValidateNested({ each: true })
  @Type(() => CohortDto)
  cohorts: CohortDto[];
}

In this example, NestJS will validate:

  • Whether CreateLegioDto.cohorts is an array of valid CohortDto
  • Whether each CohortDto.soldiers is an array of valid SoldierDto
  • Whether each SoldierDto.primaryWeapon is a valid WeaponDto

Nested Error Messages

When nested validation fails, NestJS returns a detailed error with the path to the problematic field:

// Example error response:
{
  "statusCode": 400,
  "message": [
    "cohorts.0.soldiers.1.name should not be empty",
    "cohorts.0.soldiers.1.primaryWeapon.damage must be at least 1"
  ],
  "error": "Bad Request"
}

Deep inspection is a key skill for gate guards. Without it, a malicious user could smuggle invalid data inside nested objects!

Code for this lesson: src/nested-validation.ts
// Nested validation - Deep inspection
import {
  IsString,
  IsNotEmpty,
  IsNumber,
  Min,
  Max,
  IsArray,
  ArrayMinSize,
  ValidateNested,
  IsOptional,
  IsEnum,
} from 'class-validator';
import { Type } from 'class-transformer';

// Weapon DTO
class WeaponDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsNumber()
  @Min(1)
  @Max(100)
  damage: number;
}

// TODO: Complete the soldier DTO with nested validation
class SoldierDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  @IsNumber()
  @Min(16)
  age: number;

  // TODO: Add @ValidateNested() and @Type(() => WeaponDto)
  primaryWeapon: WeaponDto;

  // TODO: Add @IsOptional(), @ValidateNested(), @Type(() => WeaponDto)
  secondaryWeapon?: WeaponDto;
}

// TODO: Complete the cohort DTO with an array of nested objects
class CohortDto {
  @IsString()
  @IsNotEmpty()
  name: string;

  // TODO: Add @ValidateNested({ each: true })
  // TODO: Add @Type(() => SoldierDto)
  // TODO: Add @IsArray() and @ArrayMinSize(3)
  soldiers: SoldierDto[];
}

console.log('Nested validation checks objects in depth!');
console.log('Remember: @ValidateNested requires @Type!');

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the @ValidateNested() decorator in class-validator do?

  2. 2. Why does @ValidateNested() require @Type() from class-transformer?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Complete the nested validation decorators in SoldierDto and CohortDto

  • Vertical ordering

    Arrange the nested validation levels from outermost to innermost:

  • Click in order

    Arrange the decorators for the soldiers field in CreateLegioDto in the correct order:

  1. Question@ValidateNested Decorator
  2. Question@Type Requirement with @ValidateNested
  3. Coding taskNested Object Validation
  4. Put in orderNested Validation Depth
  5. QuestionNested Array Validation
  6. Click in orderBuilding a Nested DTO

Useful articles