使用 NestJS 类验证器处理 null 或空字符串值

问题描述 投票:0回答:1

我在 NestJS 项目中使用类验证器,并面临有关验证的问题。我希望允许属性接受 null、''(空字符串)或 undefined 等值,无需验证。但如果有任何其他值,它应该通过验证装饰器。

以下是属性示例:

@ApiProperty({ required: false })
@IsNumber()
@IsOptional()
sample_result?: number;

@ApiProperty({ required: false })
@IsString()
@IsOptional()
sample_comment?: string;

即使使用 @IsOptional() 和 @ValidateIf() 装饰器,我也没有实现所需的行为。如果我为sample_result发送空值,它仍然会抛出如下错误:

"isNumber": "sample_result must be a number conforming to the specified constraints"

是否有人遇到过类似的问题或知道如何绕过对 null、'' 和未定义值的验证,同时对其他值强制执行验证?

我尝试在 NestJS 应用程序中使用类验证器中的 @IsOptional() 装饰器,以允许属性接受 null、''(空字符串)或 undefined 等值,而无需任何验证。我的期望是,如果我提供这些值中的任何一个,验证将绕过而不会出现任何错误。

但是,如果提供了任何其他值(例如数字字段的字符串),我希望它能够经过验证,并在与验证规则不匹配时抛出错误。

尽管使用了 @IsOptional() 装饰器,但每当我为用 @IsNumber() 装饰的属性发送空值时,我都会收到错误:

"isNumber": "sample_result must be a number conforming to the specified constraints"

这不是我所期望的,因为我假设 @IsOptional() 会允许空值而没有任何问题。

nestjs dto class-validator
1个回答
0
投票

如果您希望允许属性接受 null、''(空字符串)或未定义等值而不进行验证。 @IsOptional() 装饰器将允许 null 值,但不考虑空字符串 ('') 或未定义的值。

您可以像这样使用自定义验证装饰器 @ValidateIf() 装饰器。

 @ValidateIf((o, value) => value !== null && value !== undefined && value !== '')
© www.soinside.com 2019 - 2024. All rights reserved.