Search code examples
nestjsclass-validator

How can I resolve nestjs class-validator


The nestjs class-validator does not work. For example, if I send a post request with a number for LoginId, I get a normal response.

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

export class LoginUserDto {
  @IsString()
  loginId: string;

  @IsString()
  password: string;
}


Solution

  • class-validator needs to work with Pipe.

    You can refer to the following code to inject APP_PIPE or see the nestjs/pipe doc.

    import { Module, ValidationPipe } from '@nestjs/common';
    import { APP_PIPE } from '@nestjs/core';
    import { AppController } from './app.controller';
    import { AppService } from './app.service';
    
    @Module({
      imports: [],
      controllers: [AppController],
      providers: [
        AppService,
        {
          provide: APP_PIPE,
          useValue: new ValidationPipe({
            whitelist: true,
          }),
        },
      ],
    })
    export class AppModule {}