Search code examples
typescriptnestjsdtoclass-validator

Nestjs class validator dto validate body parameters


Hey guys i have a DTO for validate body parameters. For example;

import { IsNotEmpty, IsString } from 'class-validator';
import { ApiProperty } from '@nestjs/swagger';

export class RejectChecklistDto {
  @IsString()
  @IsNotEmpty()
  @ApiProperty({
    example: '62d7c686b6c7ed853a33adcc',
    description: 'Checklist ID',
  })
  _id: string;
}

I am sending a post request in this method like this;

{
    "_id" : "1",
    "test" : ""
}

The problem here is that class validator accepts it. I want to throw BadRequest or something because test is not defined in dto. Can you guys help me?


Solution

  • Do you may used in main.ts

    whitelist: boolean

    If set to true, validator will strip validated (returned) object of any properties that do not use any validation decorators.

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

    forbidNonWhitelisted: boolean

    If set to true, instead of stripping non-whitelisted properties validator will throw an exception.

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

    forbidUnknownValues: boolean

    If set to true, attempts to validate unknown objects fail immediately.

    app.useGlobalPipes(new ValidationPipe({ forbidUnknownValues: true }));