Skip to content
Advertisement

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:

JavaScript

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

JavaScript

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

Advertisement

Answer

You are expecting positions: [1] to throw a 400 but instead it is accepted.

According to this Github issue, this seems to be a bug in class-validator. If you pass in a primitive type (boolean, string, number,…) or an array instead of an object, it will accept the input as valid although it shouldn’t.


I don’t see any standard workaround besides creating a custom validation decorator:

JavaScript

and then use it in your dto class:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement