반응형

If class-validator is not working in your Nest.js application, there are a few things you can try:

  1. Ensure that you have installed the class-validator package by running npm install class-validator or yarn add class-validator.
  2. Ensure that you have imported the ValidationPipe from the @nestjs/common package and added it to the main.ts file in your application. The ValidationPipe will automatically use class-validator to validate incoming requests. Here's an example of what the main.ts file might look like:
  3. javascriptCopy code
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';

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

4. Ensure that you have added the @UsePipes decorator to your controller methods that need validation. Here's an example of how you might use the @UsePipes decorator:In this example, the @UsePipes decorator is used to apply the ValidationPipe to the create method of the CatsController. The ValidationPipe will automatically validate the catRequestDto parameter using the validation rules defined in the CatRequestDto class.

 

5.lessCopy code

import { Controller, Post, UsePipes, Body } from '@nestjs/common';
import { CatRequestDto } from './dto/cat-request.dto';
import { ValidationPipe } from '@nestjs/common';

@Controller('cats')
export class CatsController {
  @Post()
  @UsePipes(new ValidationPipe())
  async create(@Body() catRequestDto: CatRequestDto) {
    // code to create a new cat
  }
}​

I hope these tips help resolve your issue with class-validator in your Nest.js application. If you're still having trouble, feel free to provide more details and I'll do my best to assist you further.

+ Recent posts