Aus dem Quell-Repository gerendert; Überschriften, Beispiele, Code, Tabellen, Links und Bilder bleiben erhalten.
Validating NestJS DTOs
When to use
- Adding or refactoring DTOs
- Hardening boundary input
- Removing manual validation from controllers
Core rules
- Global
ValidationPipewithwhitelist: true,forbidNonWhitelisted: true - DTOs use
class-validatordecorators:@IsEmail(),@IsString(),@MinLength() - Use
@Type()from class-transformer for type conversion - No manual validation in controllers
- DTOs in
application/dtos/folder
Reference shape (TypeScript)
DTO with class-validator
import { IsEmail, IsString, MinLength, IsEnum } from 'class-validator';
import { Type } from 'class-transformer';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(12)
password: string;
@IsEnum(['user', 'admin'])
role: string;
}Global ValidationPipe
// main.ts
app.useGlobalPipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: { enableImplicitConversion: true },
})
);Examples — Do
@Post()
async create(@Body() dto: CreateUserDto): Promise<ApiResponse<User>> {
return toApiResponse(await this.useCase.execute(dto)); // No manual validation
}Examples — Don't
// ❌ Manual validation in controller
@Post()
create(@Body() body: any) {
if (!body.email) return { error: 'Email required' }; // No!
}Checklist
- [ ] Global ValidationPipe configured
- [ ] DTOs with class-validator decorators
- [ ] No manual validation in controllers
- [ ] DTOs in application/dtos folder
See reference/dto-patterns.md for full patterns.

