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
  }),
);
OptionEffect
whitelistRemoves unknown fields like isAdmin silently
forbidNonWhitelistedReturns 400 if unknown fields are present
transformGives you real DTO instances and converted primitives
stopAtFirstErrorOnly one message per property
disableErrorMessagesHide 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.