Validating nested objects with class-validator in NestJS

avantar

Krzysztof Szala

Posted on April 2, 2021

Validating nested objects with class-validator in NestJS

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;
}
Enter fullscreen mode Exit fullscreen mode

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;
}
Enter fullscreen mode Exit fullscreen mode

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[];
}
Enter fullscreen mode Exit fullscreen mode

Hope it will be useful for you! Cheers!

💖 💪 🙅 🚩
avantar
Krzysztof Szala

Posted on April 2, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related