Careeroza
ValidationPipe Options
Turn Validation On Globally
src/main.ts
import { ValidationPipe } from '@nestjs/common';
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // strip properties without decorators
forbidNonWhitelisted: true, // ...or reject the request instead of stripping
transform: true, // turn the plain body into a CreateProductDto instance, convert types
transformOptions: { enableImplicitConversion: true }, // "5" -> 5 for query/params based on TS type
}),
);| Option | Effect |
|---|---|
whitelist | Removes unknown fields like isAdmin silently |
forbidNonWhitelisted | Returns 400 if unknown fields are present |
transform | Gives you real DTO instances and converted primitives |
stopAtFirstError | Only one message per property |
disableErrorMessages | Hide details in production (rarely needed) |
whitelist in Action
Example
With whitelist: true and forbidNonWhitelisted: true, a client trying to sneak in a field is rejected:
curl -i -X POST http://localhost:3000/products -H "Content-Type: application/json" \
-d '{"name":"Fire-Boltt Ninja","price":1499,"stock":20,"category":"wearables","isFeatured":true}'Example output
HTTP/1.1 400 Bad Request
Content-Type: application/json; charset=utf-8
{"message":["property isFeatured should not exist"],"error":"Bad Request","statusCode":400}Tip: You can also apply validation to one handler only: @Body(new ValidationPipe({ groups: ['admin'] })) dto: CreateProductDto. Global is the usual choice.