在验证可选字段时,如何允许空值



我正在尝试制作一个三明治。当所有值都传递给Nest时,一切都正常很棒。我遇到麻烦的地方是将null(空字符串(传递给枚举,理所当然地,这会导致验证失败。

// successful
const sandwich = {
name: 'Turkey',
...
pricing: {
requirePayment: true,
default: {
value: 2000,
unit: 'whole',
}
}
} 
// fails validation
const sandwich = {
name: 'Turkey',
...
pricing: {
requirePayment: false,  // AKA free sandwich
default: {
value: "",
unit: "",
}
}
} 
// create-sandwich.dto.ts
@ApiProperty({
description: '',
example: '',
})
@ValidateNested({
each: true,
})
@Type(() => PricingInterface)
@IsNotEmpty()
readonly pricing: PricingInterface;
// pricing.interface.ts
@ApiProperty({
description: '',
example: '',
})
@ValidateNested({
each: true,
})
@Type(() => DefaultPricingInterface)
@IsOptional()
readonly default: DefaultPricingInterface;
// default-pricing.interface.ts
@ApiPropertyOptional({
description: '',
example: '',
})
@IsEnum(PriceUnit)
@IsOptional()
readonly unit: PriceUnit;  // WHOLE, HALF
@ApiPropertyOptional({
description: '',
example: '',
})
@IsNumber()
@IsOptional()
readonly value: number;

我得到的错误是:

"pricing.default.unit必须是有效的枚举值">

我理解错误,但不确定如何满足验证规则。如果三明治是免费的,它就不会有pricing.default.unit的值。我已将属性设置为可选&如果可能的话,我想保留验证。如何允许unit为空字符串?

谢谢你的建议!

@IsOptional()表示nullundefined,不是空字符串。传递一个nullundefined,或者完全省略该字段,而不是传递一个空字符串将解决问题。您甚至可以完全省略default字段,因为您已经为default声明了@IsOptional()

最新更新