NestJSInterview preparation
Intermediate·Concept·2 min read

Why use a DTO and ValidationPipe?

Practice this question

Definition:

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.

Key points:

  • 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.

Interview point:

  • Explain the difference between stripping extra fields, rejecting them and converting values; they are separate settings.
Adapted from 03_NESTJS.md · “Why use a DTO and ValidationPipe?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.