0
0
NestjsConceptBeginner · 3 min read

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.

typescript
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.`;
  }
}
Output
User John aged 30 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.

Key Takeaways

ValidationPipe automatically checks incoming data against defined rules to keep your app safe.
Use DTO classes with decorators to specify validation rules clearly.
Apply ValidationPipe globally or on specific routes to ensure data correctness.
It helps separate validation from business logic, making code cleaner and easier to maintain.
ValidationPipe uses the class-validator library for powerful and flexible validation.