Adding Validation Rules to the DTO Class
Learn how to use class-validator decorators to incorporate validation rules into our DTO classes.
Now that we have learned how to use pipes in NestJS, let’s get back to our virtual library. In this section, we’ll use the class-validator
decorators in our DTO and ValidationPipe
to ensure data integrity in our virtual library.
Adding ValidationPipe
in main.ts
Remember what we learned in the lesson on pipes? It’s time to apply it! Update the editor below to set ValidationPipe
as a global pipe for our virtual library.
export enum Language { ENGLISH = 'en', FRENCH = 'fr', } export class Book { id: number; title: string; author: string; publicationDate: string; numberOfPages: number; language: Language; }
If you’re stuck, click the “Show Solution” button.
Using class-validator
decorators in CreateBookDto
To enforce validation of the CreateBookDto
class, we need to incorporate the following validation decorators:
import { IsDateString, IsEnum, IsNotEmpty, IsNumber, IsString } from 'class-validator';import { Language } from "src/books/entities/books.entity";export class CreateBookDto {@IsString()@IsNotEmpty()title: string;@IsString()@IsNotEmpty()author: string;@IsDateString()@IsNotEmpty()publicationDate: string;@IsNumber()@IsNotEmpty()numberOfPages: number;@IsEnum(Language)@IsNotEmpty()language: Language;}
Using class-validator
decorators in GetBookFilterDto
To apply validation to the GetBookFilterDto
class, we need to utilize the following validation decorators:
import { IsDateString, IsEnum, IsString, IsOptional } from "class-validator";import { Language } from "src/books/entities/books.entity";export class GetBookFilterDto {@IsString()@IsOptional()search?: string;@IsString()@IsOptional()author?: string;@IsDateString()@IsOptional()publication_date?: string;@IsEnum(Language)@IsOptional()language?: Language;}
The role of each decorator
Let’s explore the purpose and role of each decorator used for validation:
-
@IsString()
: The@IsString()
decorator is fundamental for properties liketitle
andauthor
in ...