NestJS course Β· Module 10: Data Validation
class-validator - Gate Guard Decorators
In this lesson4
Now that you know what validation is, it's time to learn about class-validator - a decorator library that turns ordinary DTO classes into real guard posts. Each decorator is like a separate guard specializing in a specific check.
Installation
npm install class-validator class-transformerBasic Decorators
@IsString() - the text guard
Checks whether the value is a string. It's like a guard verifying that the document is written on papyrus, not on stone:
import { IsString } from 'class-validator';
export class CreateLegionaryDto {
@IsString()
name: string; // "Marcus", 12345
}@IsNumber() - the number guard
Verifies whether the value is a number:
import { IsNumber } from 'class-validator';
export class CreateLegionaryDto {
@IsNumber()
age: number; // 25, "twenty five"
}@IsEmail() - the message guard
Checks the validity of an email address format:
import { IsEmail } from 'class-validator';
export class CreateLegionaryDto {
@IsEmail()
cursusPublicus: string; // "marcus@roma.com", "marcus"
}@IsNotEmpty() - the empty field guard
Will not let empty values through - every field must have content:
import { IsNotEmpty, IsString } from 'class-validator';
export class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
name: string; // "Marcus", "", null
}@MinLength() and @MaxLength() - the length guards
Control the minimum and maximum text length:
import { MinLength, MaxLength, IsString } from 'class-validator';
export class CreateLegionaryDto {
@IsString()
@MinLength(2)
@MaxLength(50)
name: string; // "Marcus", "M", "A".repeat(51)
}Combining Decorators
The real power of class-validator lies in combining multiple decorators on a single field. It's like several guards checking different aspects of one document:
import {
IsString,
IsNotEmpty,
MinLength,
MaxLength,
IsNumber,
IsEmail,
Min,
Max,
} from 'class-validator';
export class CreateLegionaryDto {
@IsString()
@IsNotEmpty()
@MinLength(2)
@MaxLength(50)
name: string;
@IsString()
@IsNotEmpty()
rank: string;
@IsNumber()
@Min(16)
@Max(65)
age: number;
@IsEmail()
cursusPublicus: string;
@IsString()
@IsNotEmpty()
legio: string;
}Custom Error Messages
Each decorator accepts an optional parameter with an error message - so the guard can explain what's wrong:
export class CreateLegionaryDto {
@IsString({ message: 'Name must be a text, legionary!' })
@IsNotEmpty({ message: 'Name cannot be empty!' })
@MinLength(2, { message: 'Name must have at least 2 characters!' })
name: string;
@IsNumber({}, { message: 'Age must be a number!' })
@Min(16, { message: 'You must be at least 16 years old to join the legion!' })
age: number;
}Thanks to class-validator, you create a strong guard that automatically rejects invalid data before it reaches the business logic. In the next lesson, you will learn advanced decorators!
Code for this lesson: src/basic-decorators.ts
// class-validator - Basic guard decorators
import {
IsString,
IsNotEmpty,
IsNumber,
IsEmail,
MinLength,
MaxLength,
Min,
Max,
} from 'class-validator';
// Legionary recruitment DTO
export class CreateLegionaryDto {
@IsString({ message: 'Name must be a string!' })
@IsNotEmpty({ message: 'Name cannot be empty!' })
@MinLength(2, { message: 'Name must have at least 2 characters!' })
@MaxLength(50)
name: string;
@IsString()
@IsNotEmpty()
rank: string;
@IsNumber({}, { message: 'Age must be a number!' })
@Min(16, { message: 'Minimum 16 years to join the legion!' })
@Max(65)
age: number;
@IsEmail({}, { message: 'Invalid email!' })
cursusPublicus: string;
}
// TODO: Create CreateTributeDto class with fields:
// - provinceName: string (required, min 3 characters)
// - amount: number (min 1, max 10000)
// - collectorEmail: string (must be email)
// - description: string (optional, max 200 characters)
export class CreateTributeDto {
// Add validation decorators here
}
console.log('class-validator decorators ready!');
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 @IsString() decorator from the class-validator library do?
2. What is the effect of using the @IsNotEmpty() decorator?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Complete the missing validation decorators in the CreateMessengerDto class
- Vertical ordering
Arrange the validation decorators for the 'name' field from the most general to the most specific:
- Code editor
Complete the decorators with custom error messages in CreateTaxCollectorDto
- Click in order
Arrange the steps for installing and configuring validation in NestJS: