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.