0
0
NestJSframework~7 mins

ValidationPipe in depth in NestJS

Choose your learning style9 modes available
Introduction

ValidationPipe helps check if the data sent to your NestJS app is correct and safe before using it.

When you want to make sure user input follows certain rules, like required fields or correct types.
When you want to automatically transform input data into the right format or class.
When you want to stop bad or incomplete data from reaching your app logic.
When you want to send clear error messages if input data is wrong.
When you want to keep your app secure by validating all incoming requests.
Syntax
NestJS
new ValidationPipe(options?)

You create a ValidationPipe instance and pass optional settings to customize validation.

Common options include whitelist, forbidNonWhitelisted, transform, and exceptionFactory.

Examples
Basic use: applies validation globally with default settings.
NestJS
app.useGlobalPipes(new ValidationPipe());
Removes properties not in DTO and throws error if extra properties are sent.
NestJS
new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true });
Automatically converts input data types to match DTO types.
NestJS
new ValidationPipe({ transform: true });
Customizes the error message returned when validation fails.
NestJS
new ValidationPipe({ exceptionFactory: (errors) => new BadRequestException('Custom error') });
Sample Program

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.

NestJS
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.`;
  }
}
OutputSuccess
Important Notes

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.

Summary

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.