...

/

Adding Validation Rules to the DTO Class

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;
}
Integrate ValidationPipe as a global pipe for our virtual library

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:

Press + to interact
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 ...