I am currently using nest.js for my project while Mongo acting as DB. How to validate invalid payload in the class-validator? Joi package has the inbuilt support for this
import { IsString, IsInt, IsOptional } from 'class-validator';
export class CreateMovieDto {
@IsString()
readonly title: string;
@IsInt()
readonly year: number;
@IsString()
@IsOptional()
readonly plot: string;
}
My payload:
{
"title": "Interstellar",
"year": 2014,
"director": "Christopher Nolan"
}
Here I've not mentioned director in the dto. But it is inserting automatically. I don't want to use @Exclude() by restricting named properties.
If you want to just exclude unknown values during validation, you can use whitelisting
.
Even if your object is an instance of a validation class it can contain additional properties that are not defined. If you do not want to have such properties on your object, pass special flag to validate method.
This will strip all properties that don't have any decorators
https://github.com/typestack/class-validator#whitelisting
Since you are using NestJS, you can use ValidationPipe
for this:
@UsePipes(
new ValidationPipe({
whitelist: true,
}),
)
If you want to throw a validation error instead when an unknown value occurs, you can use forbidNonWhitelisted
.
@UsePipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
)