Why use a DTO and ValidationPipe?
Practice this questionDefinition:
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.
-
whiteliststrips fields without validation decorators; withforbidNonWhitelisted, extra fields cause an error. -
transformconverts 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:
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.