CodePark/ questions / Pipes, DTOs & validation
START PRACTICINGPRACTICE
Backend question · NestJS › Pipes, DTOs & validation

How do you validate request bodies with DTOs and ValidationPipe? Explain the whitelist, forbidNonWhitelisted and transform options.

export class CreateUserDto {
  @IsEmail() email: string;
  @IsString() @MinLength(8) password: string;
  @IsOptional() @IsInt() age?: number;
}

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

You write a DTO (data transfer object) class and put class-validator decorators on its properties. Then ValidationPipe does three things:

  • It uses class-transformer to turn the plain body into an instance of the DTO class.
  • It runs the validators.
  • If any validator fails, it throws a 400 error with the error messages.

DTOs must be classes, because interfaces don't exist at runtime.

The options:

  • whitelist: true removes properties that have no validation decorator. This stops clients from sending extra fields like isAdmin.
  • forbidNonWhitelisted: true rejects the request with an error, instead of silently removing those fields. It only works together with whitelist.
  • transform: true gives the handler a real DTO instance instead of a plain object. It also converts primitive params to their declared type, like @Param("id") id: number.
  • DTO classes use class-validator decorators.
  • class-transformer builds the instance, and invalid input gives a 400 error.
  • whitelist removes properties that have no decorator.
  • forbidNonWhitelisted throws an error instead of removing them.
  • transform gives real DTO instances and converts primitive params.