Class Validator & Validation Pipe

Introduction

  • We can add a few decorators to the dto class to validate the body and query by using class-validator & class-transformer library

import {
  IsArray,
  IsBoolean,
  IsNotEmpty,
  IsNumber,
  IsString,
  ValidateNested,
  IsObject,
} from 'class-validator';

import { Transform, Type } from 'class-transformer';

export class TestItem {
  @IsString()
  name: string;
}

export class WhereDto {
  @IsString()
  name: string;
  @IsBoolean()
  @Transform((value) => value.value === 'test')
  isTest: boolean;
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => TestItem)
  arr: TestItem[];
  @IsObject()
  @ValidateNested()
  @Type(() => TestItem)
  obj: TestItem;
}
  • The request body suppose should be

  • The output will be

Validation pipe

  • It is best practice to validate the correctness of any data sent into a web application. To automatically validate incoming requests, Nest provides several pipes available right out-of-the-box:

    • ValidationPipe

    • ParseIntPipe

    • ParseBoolPipe

    • ParseArrayPipe

    • ParseUUIDPipe

    The ValidationPipe makes use of the powerful class-validator package and its declarative validation decorators. The ValidationPipe provides a convenient approach to enforce validation rules for all incoming client payloads, where the specific rules are declared with simple annotations in local class/DTO declarations in each module.

Last updated

Was this helpful?