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-transformerto 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: trueremoves properties that have no validation decorator. This stops clients from sending extra fields likeisAdmin.forbidNonWhitelisted: truerejects the request with an error, instead of silently removing those fields. It only works together withwhitelist.transform: truegives 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-validatordecorators. class-transformerbuilds the instance, and invalid input gives a 400 error.whitelistremoves properties that have no decorator.forbidNonWhitelistedthrows an error instead of removing them.transformgives real DTO instances and converts primitive params.
Read more
- Validation (https://docs.nestjs.com/techniques/validation)docs.nestjs.com