Daniel ORTIZ
Daniel ORTIZ

Reputation: 2520

How to enable DTO validators in NEST JS

I'm new in NEST JS, and now i'm try to include some validator in DTO'S looks like:


// /blog-backend/src/blog/dto/create-post.dto.ts
import { IsEmail, IsNotEmpty, IsDefined } from 'class-validator';
export class CreatePostDTO {
  @IsDefined()
  @IsNotEmpty()
  title: string;
  @IsDefined()
  @IsNotEmpty()
  description: string;
  @IsDefined()
  @IsNotEmpty()
  body: string;
  @IsEmail()
  @IsNotEmpty()
  author: string;
  @IsDefined()
  @IsNotEmpty()
  datePosted: string;
}

But when i excute the post service like:

{
    "title":"juanita"
}

Its return good! But the validators should show and error rigth?

My post controloler

@Post('/post')
  async addPost(@Res() res, @Body() createPostDTO: CreatePostDTO) {
    console.log(createPostDTO)
    const newPost = await this.blogService.addPost(createPostDTO);
    return res.status(HttpStatus.OK).json({
      message: 'Post has been submitted successfully!',
      post: newPost,
    });
  }

My main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  
  await app.listen(5000);
}
bootstrap();

Upvotes: 8

Views: 12613

Answers (3)

Ali Sherafat
Ali Sherafat

Reputation: 3855

You also can register global pipes in app.module.ts file like this:

providers: [
    {
      provide: APP_PIPE,
      useValue: new ValidationPipe({
        // validation options
        whitelist: true,
      }),
    },
  ],

Upvotes: 3

Saurabh Lodha
Saurabh Lodha

Reputation: 21

For validating requests through the incoming dtos, you can use the @UsePipes() decorator provided by NestJS. This decorator can be applied globally (for the complete project), on individual endpoints. This is what the NestJS documentation says about it -

Pipes, similar to exception filters, can be method-scoped, controller-scoped, or global-scoped. Additionally, a pipe can be param-scoped. In the example below, we'll directly tie the pipe instance to the route param @Body() decorator.

Thus using it for your POST endpoint will help validate the request. Hope this helps.

Upvotes: 2

hoangdv
hoangdv

Reputation: 16157

Let's binding ValidationPipe at the application level, thus ensuring all endpoints are protected from receiving incorrect data. Nestjs document

Enable ValidationPipe for your application.

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common'; // import built-in ValidationPipe

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(new ValidationPipe()); // enable ValidationPipe`
  await app.listen(5000);
}
bootstrap();

Upvotes: 15

Related Questions