Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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",
like image 492
wiliamvj Avatar asked Oct 28 '25 02:10

wiliamvj


1 Answers

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 {}
like image 76
wiliamvj Avatar answered Oct 29 '25 17:10

wiliamvj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!