0
0
NestJSframework~30 mins

ValidationPipe setup in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
ValidationPipe setup
📖 Scenario: You are building a simple NestJS API that accepts user data. To keep your API safe and clean, you want to add validation to the incoming data.
🎯 Goal: Set up a ValidationPipe in your NestJS application to automatically validate incoming requests based on DTO rules.
📋 What You'll Learn
Create a DTO class with validation decorators
Create a ValidationPipe instance with whitelist enabled
Apply the ValidationPipe globally in the main application bootstrap
Ensure the application uses the DTO and validation pipe correctly
💡 Why This Matters
🌍 Real World
ValidationPipe helps keep APIs safe by checking incoming data automatically, preventing bad or unexpected data from causing errors or security issues.
💼 Career
Backend developers often use ValidationPipe in NestJS to enforce data rules and improve API reliability and security.
Progress0 / 4 steps
1
Create a User DTO with validation decorators
Create a class called CreateUserDto with two properties: username and age. Use @IsString() decorator on username and @IsInt() decorator on age from the class-validator package.
NestJS
Need a hint?

Remember to import IsString and IsInt from class-validator.

2
Create a ValidationPipe instance with whitelist enabled
Create a constant called validationPipe and assign it a new ValidationPipe instance with the option whitelist: true.
NestJS
Need a hint?

Use new ValidationPipe({ whitelist: true }) to create the pipe.

3
Apply the ValidationPipe globally in the main bootstrap function
In the bootstrap function, after creating the app with NestFactory.create(AppModule), apply the validationPipe globally using app.useGlobalPipes(validationPipe).
NestJS
Need a hint?

Use app.useGlobalPipes(validationPipe) to apply the pipe globally.

4
Use the CreateUserDto in a controller method
In a controller method, add a parameter called createUserDto of type CreateUserDto decorated with @Body() to receive and validate incoming user data.
NestJS
Need a hint?

Use @Body() createUserDto: CreateUserDto as the method parameter.