【问题标题】:Joi validate union typeJoi 验证联合类型
【发布时间】:2022-01-26 16:49:20
【问题描述】:

我有联合类型PaymentTerm:

type PaymentTerm =
    | { type: 'AdvancePayment' }
    | { type: 'PaymentGoal'; netPaymentDays: number }

我想使用Joi.alternatives 验证它:

  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

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

【问题讨论】:

    标签: node.js typescript joi


    【解决方案1】:

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

    我想使用Joi.alternatives 验证它

    您的架构可能的解决方案是:

    Joi.object().keys({
        type: Joi.string().valid('AdvancePayment', 'PaymentGoal').required(),
        netPaymentDays: Joi.alternatives().conditional('type', {
            is: 'PaymentGoal',
            then: Joi.number().required(),
            otherwise: Joi.forbidden()
        })
    });
    

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2017-05-19
      • 1970-01-01
      • 2016-04-17
      • 2018-09-24
      • 2018-02-03
      • 2020-04-26
      • 2021-02-05
      • 1970-01-01
      相关资源
      最近更新 更多