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
1npm 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:
1import { IsString } from 'class-validator';
2
3export class CreateLegionaryDto {
4 @IsString()
5 name: string; // "Marcus", 12345
6}@IsNumber() - the number guard
Verifies whether the value is a number:
1import { IsNumber } from 'class-validator';
2
3export class CreateLegionaryDto {
4 @IsNumber()
5 age: number; // 25, "twenty five"
6}@IsEmail() - the message guard
Checks the validity of an email address format:
1import { IsEmail } from 'class-validator';
2
3export class CreateLegionaryDto {
4 @IsEmail()
5 cursusPublicus: string; // "marcus@roma.com", "marcus"
6}@IsNotEmpty() - the empty field guard
Will not let empty values through - every field must have content:
1import { IsNotEmpty, IsString } from 'class-validator';
2
3export class CreateLegionaryDto {
4 @IsString()
5 @IsNotEmpty()
6 name: string; // "Marcus", "", null
7}@MinLength() and @MaxLength() - the length guards
Control the minimum and maximum text length:
1import { MinLength, MaxLength, IsString } from 'class-validator';
2
3export class CreateLegionaryDto {
4 @IsString()
5 @MinLength(2)
6 @MaxLength(50)
7 name: string; // "Marcus", "M", "A".repeat(51)
8}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:
1import {
2 IsString,
3 IsNotEmpty,
4 MinLength,
5 MaxLength,
6 IsNumber,
7 IsEmail,
8 Min,
9 Max,
10} from 'class-validator';
11
12export class CreateLegionaryDto {
13 @IsString()
14 @IsNotEmpty()
15 @MinLength(2)
16 @MaxLength(50)
17 name: string;
18
19 @IsString()
20 @IsNotEmpty()
21 rank: string;
22
23 @IsNumber()
24 @Min(16)
25 @Max(65)
26 age: number;
27
28 @IsEmail()
29 cursusPublicus: string;
30
31 @IsString()
32 @IsNotEmpty()
33 legio: string;
34}Custom Error Messages
Each decorator accepts an optional parameter with an error message - so the guard can explain what's wrong:
1export class CreateLegionaryDto {
2 @IsString({ message: 'Name must be a text, legionary!' })
3 @IsNotEmpty({ message: 'Name cannot be empty!' })
4 @MinLength(2, { message: 'Name must have at least 2 characters!' })
5 name: string;
6
7 @IsNumber({}, { message: 'Age must be a number!' })
8 @Min(16, { message: 'You must be at least 16 years old to join the legion!' })
9 age: number;
10}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
1// class-validator - Basic guard decorators
2import {
3 IsString,
4 IsNotEmpty,
5 IsNumber,
6 IsEmail,
7 MinLength,
8 MaxLength,
9 Min,
10 Max,
11} from 'class-validator';
12
13// Legionary recruitment DTO
14export class CreateLegionaryDto {
15 @IsString({ message: 'Name must be a string!' })
16 @IsNotEmpty({ message: 'Name cannot be empty!' })
17 @MinLength(2, { message: 'Name must have at least 2 characters!' })
18 @MaxLength(50)
19 name: string;
20
21 @IsString()
22 @IsNotEmpty()
23 rank: string;
24
25 @IsNumber({}, { message: 'Age must be a number!' })
26 @Min(16, { message: 'Minimum 16 years to join the legion!' })
27 @Max(65)
28 age: number;
29
30 @IsEmail({}, { message: 'Invalid email!' })
31 cursusPublicus: string;
32}
33
34// TODO: Create CreateTributeDto class with fields:
35// - provinceName: string (required, min 3 characters)
36// - amount: number (min 1, max 10000)
37// - collectorEmail: string (must be email)
38// - description: string (optional, max 200 characters)
39
40export class CreateTributeDto {
41 // Add validation decorators here
42}
43
44console.log('class-validator decorators ready!');
45Spotted 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: