【发布时间】:2022-01-14 10:38:56
【问题描述】:
我正在尝试制作三明治。当所有值都传递给 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 为空字符串?
感谢您的任何建议!
【问题讨论】:
标签: typescript nestjs