用户将以如下对象数组的形式发送联系信息,其中电话号码是可选的,而电子邮件是必需的:
{
"contact": [{
"type": "phone",
"value": "555-555-5555"
}, {
"type": "email",
"value": "test@test.com"
}]
}我希望确保数组中有一个电子邮件对象。我尝试了如下的Joi验证:
contact: Joi.array().items(Joi.object().keys({
type: Joi.string().valid('phone', 'email'),
value: Joi.string()
.when('contact.type', { is: 'phone', then: Joi.string() })
.when('contact.type', { is: 'email', then: Joi.string().email().required() })
}))
.when('contact.type', { is: 'phone', then: Joi.array().min(2).required() }),但我得到以下错误:
Error: Item cannot come after itself: contact它似乎不喜欢我以这种方式给它一个长度,但我想不出任何其他方法来做到这一点。任何帮助都将不胜感激。谢谢。
发布于 2021-07-05 18:42:47
这个结合了.when、.has和.unique的模式应该可以工作:
Joi.object({
contact: Joi.array().items(
Joi.object().keys({
type: Joi.string().valid('phone', 'email').required(),
value: Joi.string().when('type', { is: 'email', then: Joi.required() })
}).required(),
)
.has(Joi.object({ type: 'email', value: Joi.exist() }))
.unique('type').min(1).max(2)
})让我们来看看规则:
这就是为什么我添加了
.has(Joi.object({ type: 'email', value: Joi.exist() }))这意味着数组必须至少有一个这样的元素。
.unique('type').min(1).max(2)该数组将包含1个元素或2个不同类型的元素。
value: Joi.string().when('type', { is: 'email', then: Joi.required() })发布于 2021-07-05 23:54:04
感谢你@soltex的回答。
首先,我不确定我们是否应该排除重复项。有些人有多个电话号码。
第二,你的回答不太奏效。这是我根据你写的内容更新的答案:
contact: Joi.array().items(Joi.object().keys({
type: Joi.string().valid('phone', 'email').required(),
value: Joi.string().required(),
}))
.has(Joi.object({ type: 'email', value: Joi.string().email() }))一旦我包含了.has方法,就没有理由包含.when方法了。我也希望电子邮件是一个有效的电子邮件,而不仅仅是它的存在。我将值更改为required,因为如果用户发送类型phone,我仍然希望他们包含该值。
再次感谢您的指导。
https://stackoverflow.com/questions/68243995
复制相似问题