DEV Community

loading...
Cover image for Validating nested objects with class-validator in NestJS

Validating nested objects with class-validator in NestJS

avantar profile image Krzysztof Szala Updated on ・1 min read

Today I have for you a rapid 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!

Discussion (2)

Collapse
shanike profile image
Collapse
avantar profile image
Krzysztof Szala Author

You’re welcome! 😄

Forem Open with the Forem app