DEV Community

Raphaël Badia
Raphaël Badia

Posted on • Edited on

9 2

Fixing class-validator issues in a new Nest js project

This weekend, I played a bit with this express-based node.js framework called Nest.

Let's remind first what is a DTO :

A DTO (Data Transfer Object) is an object that defines how the data will be sent over the network.

It defines the shape of data for a specific case, such as creating an user:


CreateuserDto {
name: 'john',
password: 'isthissecureENOUGH??123'
}

 Or updating the status of a shipping:

UpdateShippingStatusDto {
status: 'ON_HOLD'
}

So, I love the concept of DTO and I was trying to validate it using ValidationPipe, just like the doc says. It quickly went wrong:

The "class-validator" package is missing. Please, make sure to install this library ($ npm install class-validator) to take advantage of ValidationPipe.

CleanShot 2020-04-05 at 15.44.34.png

Oh. I thought it would work out of the box since ValidationPipe comes from @nest/common, but nevermind, the fix is easy :



npm install class-validator


Enter fullscreen mode Exit fullscreen mode

No more errors in my console ! I carried on and sent a POST request on my endpoint...

Nest: No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.

This one made me crazy. Should I install class-validator as a peer dependency ? Is it a problem in the yarn.lock or in package.json ?

Not at all ! It turned out that my DTO had zero validation rules !

It's that simple : if you get a No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies. when using ValidationPipe, triple-check that you have at least one validation rule.

For example:



import { IsNotEmpty } from "class-validator";

export class CreateUserDto {
    @IsNotEmpty()
    firstName: string;
    lastName: string;
}


Enter fullscreen mode Exit fullscreen mode

This stackoverflow comment saved the day. Thanks !

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
superc03 profile image
SuperC03

Thank you very much, this worked perfectly.

Collapse
 
expert profile image
Expert

Thank you for this one! Only solution I found online that actually worked to correct this problem!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay