LESSON 09 / 18·2 min readIntermediate

Why use a DTO and ValidationPipe?

Try code in the playground
01 Understand02 Recall03 Prepare

Understand the concept

A DTO describes the data a boundary accepts or returns, while ValidationPipe checks and optionally transforms incoming values at runtime. TypeScript types alone cannot validate a network payload because they are erased. Decorated DTO classes make the rules available to the validation mechanism.

Important ideas

  • A DTO describes accepted input; validation decorators check it at runtime.

  • whitelist strips fields without validation decorators; with forbidNonWhitelisted, extra fields cause an error.

  • transform converts payloads to DTO instances; use explicit conversion rules where needed.

  • Validate nested objects explicitly and remember that converting a value does not automatically make it valid.

Example — DTO and global validation setup:

TypeScript
import { ValidationPipe } from '@nestjs/common';
import { IsEmail, IsString, MinLength } from 'class-validator';

class CreateUserDto {
  @IsEmail()
  email!: string;

  @IsString()
  @MinLength(2)
  name!: string;
}

// In bootstrap, after creating the Nest application:
app.useGlobalPipes(new ValidationPipe({
  whitelist: true,
  forbidNonWhitelisted: true,
  transform: true,
}));
  • A controller must use this DTO as its input type for these rules to apply; the example rejects extra fields instead of silently accepting them.
PAUSE & RECALL

Can you explain it without the notes?

Why use a DTO and ValidationPipe?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

A DTO describes the data a boundary accepts or returns, while ValidationPipe checks and optionally transforms incoming values at runtime. TypeScript types alone cannot validate a network payload because they are erased. Decorated DTO classes make the rules available to the validation mechanism.

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain the difference between stripping extra fields, rejecting them and converting values; they are separate settings.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: How should authentication and permissions work?

Adapted from 03_NESTJS.md · “Why use a DTO and ValidationPipe?”. Examples are study fragments; framework behavior can depend on your version.