ValidationPipe helps check if the data sent to your NestJS app is correct and safe before using it.
ValidationPipe in depth in NestJS
new ValidationPipe(options?)
You create a ValidationPipe instance and pass optional settings to customize validation.
Common options include whitelist, forbidNonWhitelisted, transform, and exceptionFactory.
app.useGlobalPipes(new ValidationPipe());
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true });new ValidationPipe({ transform: true });new ValidationPipe({ exceptionFactory: (errors) => new BadRequestException('Custom error') });This example shows a controller with a POST route to create a user.
The CreateUserDto class defines rules: name must be a string, age must be an integer between 1 and 120.
The ValidationPipe is used to check the input and convert types automatically.
If input is valid, it returns a message with the user's name and age.
import { Controller, Post, Body, UsePipes, ValidationPipe, BadRequestException } from '@nestjs/common'; import { IsString, IsInt, Min, Max } from 'class-validator'; class CreateUserDto { @IsString() name: string; @IsInt() @Min(1) @Max(120) age: number; } @Controller('users') export class UsersController { @Post() @UsePipes(new ValidationPipe({ whitelist: true, transform: true })) createUser(@Body() createUserDto: CreateUserDto) { return `User ${createUserDto.name} is ${createUserDto.age} years old.`; } }
Always use DTO classes with validation decorators for best results.
Enable whitelist to remove unwanted properties automatically.
Use transform to convert strings to numbers or other types as needed.
ValidationPipe checks and cleans incoming data before your app uses it.
It helps keep your app safe and your data correct.
You can customize how it works with options like whitelist and transform.
Practice
ValidationPipe in a NestJS application?Solution
Step 1: Understand ValidationPipe role
ValidationPipe is designed to validate and sanitize incoming request data to ensure it meets expected rules.Step 2: Compare with other options
Options B, C, and D relate to other parts of NestJS or web apps, not data validation.Final Answer:
To check and clean incoming data before it is used -> Option AQuick Check:
ValidationPipe purpose = data validation [OK]
- Confusing ValidationPipe with authentication or database handling
- Thinking ValidationPipe serves static files
- Assuming ValidationPipe manages sessions
ValidationPipe in NestJS?Solution
Step 1: Identify transform option
Thetransform: trueoption enables automatic conversion of input data types to expected types.Step 2: Understand other options
whitelistremoves unwanted properties,forbidNonWhitelistedthrows error on extra props,skipMissingPropertiesskips validation for missing props.Final Answer:
new ValidationPipe({ transform: true }) -> Option CQuick Check:
transform option enables type conversion [OK]
- Confusing whitelist with transform
- Using forbidNonWhitelisted to transform data
- Thinking skipMissingProperties enables transformation
class UserDto {
@IsInt()
age: number;
}
// In controller
@Post()
create(@Body(new ValidationPipe({ transform: true })) user: UserDto) {
return typeof user.age;
}Solution
Step 1: Check ValidationPipe transform option
Transform is true, so input string "25" will be converted to number 25.Step 2: Determine returned type
Since age is transformed to number,typeof user.agereturns "number".Final Answer:
"number" -> Option DQuick Check:
transform converts string to number, so typeof = "number" [OK]
- Assuming input stays string without transform
- Expecting validation error for string number
- Thinking age is undefined without explicit conversion
@Post()
create(@Body(new ValidationPipe({ whitelist: true })) user: UserDto) {
return user;
}
// UserDto has properties: name (string), age (number)Request body: { "name": "Alice", "age": 30, "extra": "value" }
Solution
Step 1: Understand whitelist behavior
Whitelist removes properties not in DTO silently without error.Step 2: Check how to throw error on extra props
To throw error on extra properties,forbidNonWhitelisted: truemust be set.Final Answer:
The ValidationPipe should have forbidNonWhitelisted to throw error on extra props -> Option AQuick Check:
forbidNonWhitelisted throws error on extra props [OK]
- Thinking whitelist throws error by default
- Ignoring need for forbidNonWhitelisted option
- Confusing whitelist with transform option
Solution
Step 1: Identify needed options
Whitelist removes extra props, transform converts types, forbidNonWhitelisted throws error on extra props.Step 2: Match options to requirements
Only new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }) includes all three: whitelist, transform, and forbidNonWhitelisted.Final Answer:
new ValidationPipe({ whitelist: true, transform: true, forbidNonWhitelisted: true }) -> Option BQuick Check:
Whitelist + transform + forbidNonWhitelisted = strict validation [OK]
- Omitting forbidNonWhitelisted to throw errors
- Forgetting transform for type conversion
- Using skipMissingProperties instead of forbidNonWhitelisted
Ready to prove it?
Pass the test and this pattern moves unknown
