What is ValidationPipe in NestJS: Simple Explanation and Example
ValidationPipe in NestJS is a built-in tool that automatically checks and validates incoming data against defined rules before your code uses it. It helps keep your app safe and clean by ensuring data is correct and formatted as expected.How It Works
Think of ValidationPipe as a security guard at the entrance of your app's data. When data comes in, this guard checks if it meets certain rules you set, like making sure a name is a string or an age is a number. If the data passes the check, it moves inside your app; if not, the guard stops it and sends back an error.
This process happens automatically when you add ValidationPipe to your route handlers or globally in your NestJS app. It uses special classes called DTOs (Data Transfer Objects) where you define the rules using decorators. This way, your app only works with clean and expected data, reducing bugs and security risks.
Example
This example shows how to use ValidationPipe to check user input for creating a new user. The DTO defines rules, and the pipe validates the data automatically.
import { Controller, Post, Body, UsePipes, ValidationPipe } 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()) createUser(@Body() createUserDto: CreateUserDto) { return `User ${createUserDto.name} aged ${createUserDto.age} created successfully.`; } }
When to Use
Use ValidationPipe whenever your app receives data from outside sources like user forms, APIs, or external services. It ensures the data is safe and correct before your app processes it.
For example, when users sign up or submit forms, ValidationPipe checks their input to avoid errors or malicious data. It also helps keep your code clean by separating validation logic from business logic.
Key Points
- Automatic validation: Checks data against rules without extra code.
- Uses DTOs: Define clear rules with decorators.
- Improves security: Stops bad data early.
- Easy to apply: Use globally or per route.
- Built on class-validator: Leverages a popular validation library.