Basic validation

Let's add basic rules for the incoming data.

Let's create a module called common to deal with everything not pertaining to a more specific location, such as some global enhancers.

nest g mo common

Inside it, in the providers array, we can insert a global instance of the ValidationPipe, which we'll improve soon.

{
  provide: APP_PIPE,
  useValue: new ValidationPipe(),
}

With this, validation is now possible. Let's install the required dependencies to continue.

yarn add class-validator class-transformer

Now, remember the create-user.dto file? It is a DTO (Data Transfer Object), in this case encapsulating the fields required to create a user. Generally, DTOs are used to hold only the essential data to do something. Hence the id was omitted, as it is automatically generated. We will also use them to define how we want to validate these same fields, and it's what we'll do right now.

All of these fields are strings, so we can begin by decorating them with the @IsString() decorator, like so

@IsString()
readonly name: string;

Now, all of them are required and must be strings. We have basic validation working. Subsequent sections will focus on several improvements to what we currently have.

Last updated