0
0
NestJSframework~5 mins

ValidationPipe setup in NestJS

Choose your learning style9 modes available
Introduction

ValidationPipe helps check if the data sent to your app is correct and safe. It stops bad data before it causes problems.

When you want to make sure user input matches expected rules, like required fields or correct types.
When you want to automatically convert input data to the right type, like turning strings into numbers.
When you want to reject requests with wrong or missing data early, so your app stays stable.
When you want to add simple error messages for invalid input without writing extra code.
When you want to keep your app secure by validating all incoming data.
Syntax
NestJS
app.useGlobalPipes(new ValidationPipe({ options }))

You add ValidationPipe globally in your main.ts file to check all incoming requests.

You can pass options to customize behavior, like whitelist or transform.

Examples
Basic setup with default validation rules.
NestJS
app.useGlobalPipes(new ValidationPipe())
Removes any properties that are not in the DTO (data transfer object).
NestJS
app.useGlobalPipes(new ValidationPipe({ whitelist: true }))
Automatically converts input types to match DTO types, like string to number.
NestJS
app.useGlobalPipes(new ValidationPipe({ transform: true }))
Rejects requests with extra properties not in the DTO and removes them.
NestJS
app.useGlobalPipes(new ValidationPipe({ forbidNonWhitelisted: true, whitelist: true }))
Sample Program

This code sets up a NestJS app and adds ValidationPipe globally. It removes extra properties and converts input types automatically.

NestJS
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
  await app.listen(3000);
}

bootstrap();
OutputSuccess
Important Notes

Always create DTO classes with validation decorators like @IsString(), @IsInt() to use ValidationPipe effectively.

Use whitelist: true to keep only allowed properties and improve security.

Use transform: true to get correct data types without manual conversion.

Summary

ValidationPipe checks and cleans incoming data automatically.

Set it up globally in main.ts for all routes.

Use options like whitelist and transform to customize validation behavior.