nestjsclass-validatorclass-transformer

Class Validator is not working with nestjs


I have some projects with nestjs, I've always used the class validator, but recently it doesn't seem to be working. It simply doesn't call the DTO to validate.

controller

@Post()
  async create(@Body() body: UserDTO) {
    return body;
  }

My DTO

import { IsNotEmpty, IsString } from 'class-validator';

export class UserDTO {
  @IsNotEmpty()
  @IsString()
  name: string;
}

main

app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

versions class validator and class transformer

"class-transformer": "^0.5.1",
"class-validator": "^0.13.2",

Solution

  • Solved, the solution was to instantiate the validation pipe inside the input module

    @Module({
      imports: [ConfigModule.forRoot(), UserModule, AuthModule],
      controllers: [],
      providers: [
        {
          provide: APP_PIPE,
          useValue: new ValidationPipe({
            whitelist: true,
            forbidNonWhitelisted: true,
            transform: true,
          }),
        },
      ],
    })
    export class AppModule {}