Class Validator & Validation Pipe
Introduction
We can add a few decorators to the
dtoclass to validate the body and query by usingclass-validator&class-transformerlibrary
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:
ValidationPipeParseIntPipeParseBoolPipeParseArrayPipeParseUUIDPipe
The
ValidationPipemakes use of the powerful class-validator package and its declarative validation decorators. TheValidationPipeprovides 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?