Why use a DTO and ValidationPipe?
Try code in the playgroundUnderstand 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.
-
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.
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.
Turn this concept into a clear answer.
- Explain the difference between stripping extra fields, rejecting them and converting values; they are separate settings.
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.