gpt4 book ai didi

How to validate a request in class-validator if a property in payload doesn't match the dto Object?(如果有效负载中的属性与dto对象不匹配,如何在类验证器中验证请求?)

转载 作者:bug小助手 更新时间:2023-10-25 21:31:45 28 4
gpt4 key购买 nike



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

我目前正在为我的项目使用nest.js,而Mongo则充当数据库。如何在类验证器中验证无效负载?Joi包具有对此的内置支持


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.

这里我没有在dto中提到导演。但它是自动插入的。我不想通过限制命名属性来使用@Exclude()。


更多回答
优秀答案推荐

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:

由于您使用的是NestJS,因此可以使用ValidationTube执行以下操作:


@UsePipes(
new ValidationPipe({
whitelist: true,
}),
)



If you want to throw a validation error instead when an unknown value occurs, you can use forbidNonWhitelisted.

如果您希望在出现未知值时引发验证错误,则可以使用forbitNonWhitelisted。


@UsePipes(
new ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
}),
)

更多回答

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com