验证可选字段时如何允许空值?
How can I allow a null value when validating an optional field?
我正在尝试做一个三明治。当所有值都传递给 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 must be a valid enum value"
我理解错误,但我不确定如何满足验证规则。如果三明治是免费的,它就不会有 pricing.default.unit
的值。我已将 属性 设置为可选,如果可能,我想保留验证。如何让 unit
为空字符串?
感谢您的任何建议!
@IsOptional()
表示 null
或 undefined
,不是空字符串。传递 null
或 undefined
,或完全省略该字段,而不是传递空字符串即可解决问题。您甚至可以完全省略 default
字段,因为您还为 default
.
声明了 @IsOptional()
我正在尝试做一个三明治。当所有值都传递给 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 must be a valid enum value"
我理解错误,但我不确定如何满足验证规则。如果三明治是免费的,它就不会有 pricing.default.unit
的值。我已将 属性 设置为可选,如果可能,我想保留验证。如何让 unit
为空字符串?
感谢您的任何建议!
@IsOptional()
表示 null
或 undefined
,不是空字符串。传递 null
或 undefined
,或完全省略该字段,而不是传递空字符串即可解决问题。您甚至可以完全省略 default
字段,因为您还为 default
.
@IsOptional()