Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate nested objects using class validator and nestjs

I'm trying to validate nested objects using class-validator and NestJS. I've already tried following this thread by using the @Type decorator from class-transform and didn't have any luck. This what I have:

DTO:

class PositionDto {   @IsNumber()   cost: number;    @IsNumber()   quantity: number; }  export class FreeAgentsCreateEventDto {    @IsNumber()   eventId: number;    @IsEnum(FinderGamesSkillLevel)   skillLevel: FinderGamesSkillLevel;    @ValidateNested({ each: true })   @Type(() => PositionDto)   positions: PositionDto[];  } 

I'm also using built-in nestjs validation pipe, this is my bootstrap:

async function bootstrap() {   const app = await NestFactory.create(ServerModule);   app.useGlobalPipes(new ValidationPipe());   await app.listen(config.PORT); } bootstrap(); 

It's working fine for other properties, the array of objects is the only one not working.

like image 531
Leonardo Emilio Dominguez Avatar asked Dec 14 '18 20:12

Leonardo Emilio Dominguez


Video Answer


1 Answers

for me, I would able to validate nested object with 'class-transformer'

import { Type } from 'class-transformer'; 

full example:

import {   MinLength,   MaxLength,   IsNotEmpty,   ValidateNested,   IsDefined,   IsNotEmptyObject,   IsObject,   IsString, } from 'class-validator'; import { Type } from 'class-transformer';  class MultiLanguageDTO {   @IsString()   @IsNotEmpty()   @MinLength(4)   @MaxLength(40)   en: string;    @IsString()   @IsNotEmpty()   @MinLength(4)   @MaxLength(40)   ar: string; }  export class VideoDTO {   @IsDefined()   @IsNotEmptyObject()   @IsObject()   @ValidateNested()   @Type(() => MultiLanguageDTO)   name!: MultiLanguageDTO; } 
like image 76
tarek noaman Avatar answered Sep 18 '22 12:09

tarek noaman