首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Joi验证联合类型

Joi验证联合类型
EN

Stack Overflow用户
提问于 2022-01-19 14:55:14
回答 1查看 667关注 0票数 1

我有联合型PaymentTerm

代码语言:javascript
复制
type PaymentTerm =
    | { type: 'AdvancePayment' }
    | { type: 'PaymentGoal'; netPaymentDays: number }

我想用Joi.alternatives验证它

代码语言:javascript
复制
  Joi.object({
    type: Joi.string().required().valid('AdvancePayment')
  }),
  Joi.object({
    type: Joi.string().required().valid('PaymentGoal'),
    netPaymentDays: Joi.number().required().messages({
      'any.required': '{{#label}} is required'
    })
  })
)

const { error, value } = schema.validate({
  type: 'PaymentGoal'
})

现在我希望得到"netPaymentDays" is required,但是我得到了"value" does not match any of the allowed types

如何获得“嵌套”错误而不是替代方案的通用错误?

EN

回答 1

Stack Overflow用户

发布于 2022-01-26 08:49:20

您已经提到了解决此问题的正确方法,但我看不到在您的示例中使用它。

我想用Joi.alternatives验证它

模式的一个可能解决方案是:

代码语言:javascript
复制
Joi.object().keys({
    type: Joi.string().valid('AdvancePayment', 'PaymentGoal').required(),
    netPaymentDays: Joi.alternatives().conditional('type', {
        is: 'PaymentGoal',
        then: Joi.number().required(),
        otherwise: Joi.forbidden()
    })
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70772805

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档