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.Since you are using NestJS, you can use
ValidationPipefor this:If you want to throw a validation error instead when an unknown value occurs, you can use
forbidNonWhitelisted.