fix: ValidatedNested with transform not validating
See original GitHub issueVersions:
- 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:
- Created 2 years ago
- Comments:6 (1 by maintainers)
Top 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 >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
For my particular issue I wanted to parse a string into an object and validate it… this works for me:
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.