NestJS course ยท Module 1: NestJS Basics
DTOs and basic validation
In this lesson8
Ave, gate guardian! Consul Caesar.js knows that the security of the Empire begins with controlling what enters through the gates. We cannot let invalid data into our system - that's like letting spies into the legion camp! Time to learn DTOs and validation - the protective shields of our API.
What are DTOs?
DTO (Data Transfer Object) is a class that defines the shape of data sent to and from our API. Think of a DTO as a legion recruitment form - every new legionary must fill in the appropriate fields before being accepted.
Without a DTO, our controller accepts anything - that's like an open gate without guards:
// WITHOUT DTO - dangerous!
@Post()
create(@Body() body: any) {
// body can contain anything... dangerous!
return this.legionariesService.create(body);
}With a DTO we precisely define what data we accept:
// WITH DTO - secure like a Roman fort!
@Post()
create(@Body() createLegionaryDto: CreateLegionaryDto) {
return this.legionariesService.create(createLegionaryDto);
}Creating DTO classes
Let's create a DTO for our legionary system:
// dto/create-legionary.dto.ts
export class CreateLegionaryDto {
name: string;
rank: string;
province: string;
email: string;
experience: number;
}However, this is only the data shape - it does not yet check whether the data is valid. This is where validation comes in!
Installing class-validator and class-transformer
To add validation, we need two libraries:
npm install class-validator class-transformer- class-validator - provides validation decorators (@IsString, @IsNumber, etc.)
- class-transformer - transforms plain JSON objects into DTO class instances
Validation decorators
Now let's add validation to our DTO:
// dto/create-legionary.dto.ts
import {
IsString, IsNumber, IsEmail,
MinLength, MaxLength, Min, Max,
IsNotEmpty, IsOptional, IsIn
} from 'class-validator';
export class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
@MinLength(2)
@MaxLength(50)
name: string;
@IsString()
@IsIn(['Miles', 'Optio', 'Centurio', 'Tribunus', 'Legatus'])
rank: string;
@IsString()
@IsNotEmpty()
province: string;
@IsEmail()
email: string;
@IsNumber()
@Min(0)
@Max(30)
experience: number;
}Here are the most commonly used validation decorators:
| Decorator | Description |
|---|---|
@IsString() | Checks if the value is a string |
@IsNumber() | Checks if the value is a number |
@IsEmail() | Checks if the value is a valid email |
@IsNotEmpty() | Checks if the field is not empty |
@MinLength(n) | Minimum text length |
@MaxLength(n) | Maximum text length |
@Min(n) | Minimum numeric value |
@Max(n) | Maximum numeric value |
@IsOptional() | Field is optional |
@IsIn([...]) | Value must be one of the given options |
Update DTO - PartialType
For partial updates (PATCH) we can use PartialType, which makes all fields optional:
// dto/update-legionary.dto.ts
import { PartialType } from '@nestjs/mapped-types';
import { CreateLegionaryDto } from './create-legionary.dto';
export class UpdateLegionaryDto extends PartialType(CreateLegionaryDto) {}
// Now all fields are optional!PartialType comes from a separate package, which you install with npm i @nestjs/mapped-types. It automatically creates a new class where every field from CreateLegionaryDto becomes optional. Thanks to this, we don't need to write a separate DTO with @IsOptional() on every field.
ValidationPipe - global validation
For validation to work, we need to activate ValidationPipe in our application:
// main.ts
import { NestFactory } from '@nestjs/core';
import { ValidationPipe } from '@nestjs/common';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe({
whitelist: true, // Removes fields that are not in the DTO
forbidNonWhitelisted: true, // Throws error when unknown fields are present
transform: true, // Automatic type conversion
}));
await app.listen(3000);
}
bootstrap();Three key ValidationPipe options:
- whitelist: true - automatically removes fields not present in the DTO (like a guard rejecting suspicious packages)
- forbidNonWhitelisted: true - instead of silently removing unknown fields, throws an error (stricter control)
- transform: true - automatically converts data to appropriate types (string "5" to number 5)
Complete controller example with DTOs
@Controller('legionaries')
export class LegionariesController {
constructor(private readonly legionariesService: LegionariesService) {}
@Post()
create(@Body() createDto: CreateLegionaryDto) {
return this.legionariesService.create(createDto);
}
@Patch(':id')
update(
@Param('id') id: string,
@Body() updateDto: UpdateLegionaryDto,
) {
return this.legionariesService.update(Number(id), updateDto);
}
}When someone sends invalid data, ValidationPipe will automatically return a readable error:
{
"statusCode": 400,
"message": [
"name must be longer than or equal to 2 characters",
"email must be an email",
"experience must not be greater than 30"
],
"error": "Bad Request"
}Why are DTOs important?
- Security - they block unwanted data before it reaches business logic
- Documentation - they clearly define the API contract
- Validation - automatic verification of data correctness
- Typing - TypeScript knows the data shape throughout the application
- Separation - they separate the transport layer from business logic
DTOs and validation are the shield and sword of our Empire - they protect the API gates and ensure that only valid data enters the system. Every good Empire builder knows that strong walls are the foundation!
Code for this lesson: src/dto-validation.ts
// DTOs and Validation - Protective Shields of the Imperium
import { IsString, IsNumber, IsEmail, MinLength, MaxLength, Min, Max, IsNotEmpty, IsOptional, IsIn } from 'class-validator';
console.log("DTOs and validation - gate guard of the imperium!");
// ===========================================
// 1. DTO - Data Transfer Object
// ===========================================
// DTO class defines the shape of data
class CreateLegionaryDto {
// @IsString()
// @IsNotEmpty()
// @MinLength(2)
// @MaxLength(50)
name: string;
// @IsString()
// @IsIn(['Miles', 'Optio', 'Centurio', 'Tribunus', 'Legatus'])
rank: string;
// @IsString()
// @IsNotEmpty()
province: string;
// @IsEmail()
email: string;
// @IsNumber()
// @Min(0)
// @Max(30)
experience: number;
}
console.log("=== CREATE LEGIONARY DTO ===");
console.log("name: @IsString, @IsNotEmpty, @MinLength(2)");
console.log("rank: @IsString, @IsIn([...])");
console.log("province: @IsString, @IsNotEmpty");
console.log("email: @IsEmail");
console.log("experience: @IsNumber, @Min(0), @Max(30)");
// ===========================================
// 2. Validation decorators
// ===========================================
console.log("\n=== VALIDATION DECORATORS ===");
console.log("@IsString() - checks if text");
console.log("@IsNumber() - checks if number");
console.log("@IsEmail() - checks if email");
console.log("@IsNotEmpty() - checks if not empty");
console.log("@MinLength(n) - minimum text length");
console.log("@MaxLength(n) - maximum text length");
console.log("@Min(n) - minimum numeric value");
console.log("@Max(n) - maximum numeric value");
console.log("@IsOptional() - optional field");
console.log("@IsIn([...]) - value from list");
// ===========================================
// 3. Update DTO with PartialType
// ===========================================
// import { PartialType } from '@nestjs/mapped-types';
// class UpdateLegionaryDto extends PartialType(CreateLegionaryDto) {}
// -> All fields become optional!
class UpdateLegionaryDto {
name?: string;
rank?: string;
province?: string;
email?: string;
experience?: number;
}
console.log("\n=== UPDATE DTO (PartialType) ===");
console.log("PartialType makes all fields optional");
console.log("Ideal for PATCH - partial update");
// ===========================================
// 4. ValidationPipe - global validation
// ===========================================
// W main.ts:
// app.useGlobalPipes(new ValidationPipe({
// whitelist: true, // Strips unknown fields
// forbidNonWhitelisted: true, // Error on unknown fields
// transform: true, // Type conversion
// }));
console.log("\n=== VALIDATION PIPE ===");
console.log("whitelist: true -> strips fields outside DTO");
console.log("forbidNonWhitelisted: true -> error on unknown fields");
console.log("transform: true -> type conversion (string -> number)");
// ===========================================
// 5. Example usage in controller
// ===========================================
console.log("\n=== CONTROLLER WITH DTO ===");
console.log("@Post()");
console.log("create(@Body() createDto: CreateLegionaryDto) { ... }");
console.log("");
console.log("@Patch(':id')");
console.log("update(@Param('id') id, @Body() updateDto: UpdateLegionaryDto) { ... }");
// ===========================================
// 6. Example validation error response
// ===========================================
const validationError = {
statusCode: 400,
message: [
"name must be longer than or equal to 2 characters",
"email must be an email",
"experience must not be greater than 30"
],
error: "Bad Request"
};
console.log("\n=== VALIDATION ERROR EXAMPLE ===");
console.log(JSON.stringify(validationError, null, 2));
console.log("\n=== SUMMARY ===");
console.log("1. DTO = data shape (API contract)");
console.log("2. class-validator = validation decorators");
console.log("3. class-transformer = object conversion");
console.log("4. ValidationPipe = automatic validation");
console.log("5. PartialType = optional fields (for PATCH)");
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What does the abbreviation DTO stand for in the NestJS context?
2. Which class-validator decorator checks if a value is a valid email address?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps for adding DTO validation in NestJS:
- Code editor
Write a CreateLegionaryDto class with name (@IsString, @IsNotEmpty) and email (@IsEmail) fields
- Click in order
Arrange the syntax for activating ValidationPipe in main.ts:
- Horizontal ordering
Arrange the elements for creating UpdateDto with PartialType:
- Code editor
In main.ts, write a setupValidation(app) function that enables global validation in the application: it calls app.useGlobalPipes() with a new ValidationPipe whose whitelist and transform options are set to true.