Butani Hardik
Butani Hardik

Reputation: 81

How to validate Dynamic key -> value DTO validation in nest js?

import { ApiProperty } from '@nestjs/swagger';
import { IsString, ValidateNested } from 'class-validator';

export class TestDto {
  @ApiProperty()
  test: string;
}

export class UserReqDto {
  @ApiProperty()
  @IsString()
  id: string;

  @ApiProperty()
  @ValidateNested({ each: true })
  data: object;
}

const sampleData = {
  id: 'asbd',
  data: {
    ['any dynamic key 1']: {
      test: '1',
    },
    ['any dynamic key 2']: {
      test: '2',
    },
  },
};

Here UserReqDto is my main DTO and TestDto is child DTO. I need to validate sampleData type of data.

How can I do that?

in data field i need to validate object of TestDto type's objects

Upvotes: 3

Views: 4025

Answers (1)

Cuong Le Ngoc
Cuong Le Ngoc

Reputation: 11975

You can use Map<string, TestDto> as type for data field:

@ApiProperty()
@ValidateNested({ each: true })
data: Map<string, TestDto>

Note: Nested object must be an instance of a class, otherwise @ValidateNested won't know what class is target of validation so you can use class-transformer to transform data value to instance of TestDto.

@ApiProperty()
@ValidateNested({ each: true })
@Type(() => TestDto)
data: Map<string, TestDto>

Upvotes: 6

Related Questions