Skip to content

fix: <@ValidateNested() Fails When Used with @Transform() in NestJS DTO Validation> #2589

Open
@nhattan1504

Description

@nhattan1504

Description

In NestJS, when using @Transform() to parse JSON-formatted form-data values while also applying @ValidateNested(), the validation process fails.

Minimal code-snippet showcasing the problem

import { Type, Transform } from 'class-transformer';
import { ArrayMinSize, IsArray, ValidateNested, IsString, IsEmail, IsEnum, IsInt } from 'class-validator';

export enum RequestType {
  SIGNER = 'SIGNER',
  VIEWER = 'VIEWER',
}

export class SignerDto {
  @IsString()
  id: string;

  @IsString()
  name: string;

  @IsEmail()
  email: string;

  @IsEnum(RequestType)
  requestType: RequestType;

  @IsInt()
  group: number;
}

export class CreateContractFromFileDto {
  @Transform(({ value }) => {
return JSON.parse(value); // Convert string to object
    })
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => SignerDto)
  signerList: SignerDto[];
}

Expected behavior

It should validate the field inside SignerDTO

Actual behavior

I tried with this

curl -X POST http://localhost:3000/contract/createContractFromFile \
  -H "Content-Type: multipart/form-data" \
  -F 'signerList=[{\"id\":\"1\",\"name\":\"John Doe\",\"email\":\"[email protected]\",\"requestType\":\"SIGNER\",\"group\":1}]'

It can not definitely a path property and fail all data value.

An instance of CreateContractFromFileDto has failed the validation:\n - property signerList[0].undefined has failed the following constraints: unknownValue

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: needs triageIssues which needs to be reproduced to be verified report.type: fixIssues describing a broken feature.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions