| name | validating-nestjs-dtos |
| description | Validates NestJS request payloads with class-validator and class-transformer using a global ValidationPipe. Use when adding/refactoring DTOs, hardening boundary input, or removing manual validation from controllers. |
| license | MIT |
Validating NestJS DTOs
When to use
- Adding or refactoring DTOs
- Hardening boundary input
- Removing manual validation from controllers
Core rules
- Global
ValidationPipe with whitelist: true, forbidNonWhitelisted: true
- DTOs use
class-validator decorators: @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
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));
}
Examples — Don't
@Post()
create(@Body() body: any) {
if (!body.email) return { error: 'Email required' };
}
Checklist
See reference/dto-patterns.md for full patterns.