question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

fix: ValidatedNested with transform not validating

See original GitHub issue

Versions:

  • class-transformer: 0.4.0
  • class-validator: 0.13.2

Description

Using Transform from class-transformer and ValidateNested of class-validator seems to skip validation of nested fields.

Minimal code-snippet showcasing the problem

import 'reflect-metadata'
import { IsInt, ValidateNested, validateSync } from 'class-validator'
import { plainToClass, Transform, Type } from 'class-transformer'

class Son {
    @IsInt()
    num!: number
}

class Parent {
    @ValidateNested()
    @Type(() => Son)
    @Transform(({ value }) => ({ num: 'a' }))
    son!: Son
}

const parent = plainToClass(Parent, { son: { num: 'abc' } })
console.log('errors: ', validateSync(parent).toString())  // Passing with no validation errors

Expected behavior

Displaying validation error - in this case not passing the isInt.

Actual behavior

Passing validation

Issue Analytics

  • State:open
  • Created 2 years ago
  • Comments:6 (1 by maintainers)

github_iconTop GitHub Comments

4reactions
manistracommented, Sep 28, 2022

For my particular issue I wanted to parse a string into an object and validate it… this works for me:

export class UploadDocumentDto {
  @ValidateNested()
  @Transform(({ value }) => plainToClass(UploadDocument, JSON.parse(value)), {
    toClassOnly: true,
  })
  @Type(() => UploadDocument)
  readonly documents: UploadDocument[];
}
export class UploadDocument {
  @IsNotEmpty()
  @IsString()
  id: string;

  @IsNotEmpty()
  @IsString()
  name: string;
}

2reactions
manistracommented, Sep 28, 2022

validation and transformations work with class instances. try this

class Parent {
    @ValidateNested()
    @Type(() => Son)
    @Transform(({ value }) => {
      // change and return the current instance of `Son` or create new one
       value.num = 'a';
       return value;
    })
    son!: Son
}

Tried

	@Transform(
		({ value }) => {
			value = JSON.parse(value);
			return value;
		},
		{ toClassOnly: true },
	)

No difference

Instead of just: return value try using: return plainToClass(DesiredClassDto, value)

For some reason { toClassOnly: true } alone doesn’t do the trick, and if I’m not wrong for values to be validated they need to be part of a dto class instance.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Validating nested objects with class-validator in NestJS
Because I wrote nested object in array more than couple layers. By the way I have fixed it by customized validate pipe when...
Read more >
NestJS transform a property using ValidationPipe before ...
The transforms seem to have no effect. Class validator tells me that each of those properties cannot be empty. If for example I...
Read more >
Combining Validators and Transformers in NestJS
There's a way to fix this in NestJS. First, let's install the dependencies needed for using data transformation and validation in NestJS:.
Read more >
How to use the class-validator.IsIn function in class-validator
Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues...
Read more >
Validation | NestJS - A progressive Node.js framework
dismissDefaultMessages, boolean, If set to true, the validation will not use ... The ValidationPipe can automatically transform payloads to be objects typed ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found