我在 NestJS 应用程序中使用类验证器,并且在某些字段上遇到了挑战。例如,我有一个字段sample_result,它可以包含一个数字,但我希望能够在某些情况下(例如,如果我想删除数据库中的值)。这同样适用于另一个字段sample_comment,它是一个字符串。
相关代码如下:
@ApiProperty({ required: false })
@IsNumber()
@IsOptional()
sample_result?: number;
@ApiProperty({ required: false })
@IsString()
@IsOptional()
sample_comment?: string;
挑战在于,当我为sample_result或sample_comment发送null或''时,我收到验证错误。类验证器的正确方法或配置是什么,以允许这些特定字段为空或空字符串,同时确保提供值时,它们遵守各自的验证(即,sample_result 的数字和sample_comment 的字符串)?
任何指导或建议将不胜感激。谢谢!
必须是字符串 必须是符合指定约束的数字
要允许特定字段为 null 或空字符串,同时仍然在 NestJS 应用程序中使用类验证器遵守各自的验证,您可以使用条件验证装饰器。
首先,从类验证器包中导入 IsNotEmpty、IsEmpty 和 IsDefined 装饰器:
import { ApiProperty } from '@nestjs/swagger';
import { IsNumber, IsString, IsOptional, ValidateIf } from 'class-validator';
export class YourDto {
@ApiProperty({ required: false })
@IsNumber()
@ValidateIf((obj) => obj.sample_result !== null && obj.sample_result !== '')
sample_result?: number | null;
@ApiProperty({ required: false })
@IsString()
@ValidateIf((obj) => obj.sample_comment !== null && obj.sample_comment !== '')
sample_comment?: string | null;
}
在更新后的代码中,我们使用 ValidateIf 装饰器根据sample_result和sample_comment的值有条件地应用验证。仅当值不为 null 或空字符串时才会应用验证。
通过添加 | null 到变量类型,我们允许在需要时将这些字段设置为 null。
现在您应该能够为sample_result和sample_comment发送null或''而不会触发验证错误,同时仍然确保提供值时,它们遵守各自的验证。
我希望这有帮助!如果您还有任何疑问,请告诉我。