Skip to main content

Validation in Nest

As part of security, it’s very important to make sure users enter valid data so that we don’t have to save incorrect or incoherent data in the password. While most of the decorators can manage validating data, sometimes, we may need a deeper check to make sure users don’t challenge our database with incorrect data, for example, we shouldn’t allow a user to enter a weak password, or we should never allow the user to enter an invalid email on the registry, etc.

Let’s see in simple use cases, how we can make our api a safer place for our clients.

First, let’s install helper packages:

# installs packages
$ yarn add class-validator class-transformer

We have added the class-validator class that contains a set of validators, that nest support very well, you can read more about that package here.

Then, let’s bind the [ValidationPipe](https://docs.nestjs.com/techniques/validation#using-the-built-in-validationpipe) at the application root level, thus ensuring all endpoints are protected from receiving incorrect data.

Then, locate our dto files that send data to the server, and make sure you validate each field, falling to do so, will fail as we asked the main file to only accept checked and valid data.

Let’s see how the create-user.dto.ts file looks like:

image16 - create user dto with validation

image16 - create user dto with validation

The file really speaks to itself, the class-validator uses intuitive names to define its decorators that we understand their use straightforwardly.

Let’s now try to create a user with incorrect information, this is what we get, the message array describes for us what went wrong.

// response when data are incorrect

{
"errors": [
{
"message": "Bad Request Exception",
"extensions": {
"code": "BAD_USER_INPUT",
"response": {
"statusCode": 400,
"message": [
"password is not strong enough"
],
"error": "Bad Request"
}
}
}
],
"data": null
}

With this simple setup, we are now able to make sure data we receive are correct, that way we keep our database coherent and clean. class-validator also provides some validators that I used like @IsMongoId() , @IsUrl() and a lot more, please take a moment to explore the list in the class-validator documentation.

You can get the codebase for the previous part by checking out the commit #812bc3