Validating nested objects with class-validator in NestJS
Krzysztof Szala
Posted on April 2, 2021
Today I have for you a quick and short article. Maybe it will help someone. I'm using class-validator for request validation in NestJS really often. A few days ago I needed to validate a nested object. Quick look to the class-validator validation:
If your object contains nested objects and you want the validator to perform their validation too, then you need to use the
@ValidateNested()
decorator:
import { ValidateNested } from 'class-validator';
export class Post {
@ValidateNested()
user: User;
}
But for some reason It doesn't work in NestJS! Here is an easy solution. Install class-transformer
package, if you haven't done it yet. Then import @Type()
decorator, and declare the type of validating object with it. Check this out:
import { ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
export class Post {
@ValidateNested()
@Type(() => User)
user: User;
}
Now our NestJS application will validate User
object correctly. If you need to validate an array of objects, use each: true
:
export class User {
@ValidateNested({ each: true })
@Type(() => Post)
posts: Post[];
}
Hope it will be useful for you! Cheers!
Posted on April 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.