HapiJS/Joi 允许字段为具有特定键的字符串或对象
HapiJS/Joi Allow field to be String or Object with specific keys
我正在尝试验证 POST 请求,其中 title
可以是 String 或 Object 与语言键和值。示例:
{
title: 'Chicken',
...
}
//OR
{
title: {
en_US: 'Chicken',
de_DE: 'Hähnchen'
}
...
}
对于 Joi,我正在尝试像这样验证:
{
title: Joi.any().when('title', {
is: Joi.string(),
then: Joi.string().required(),
otherwise: Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
}).required()
}),
...
}
但是,当我尝试验证时出现错误 AssertionError [ERR_ASSERTION]: Item cannot come after itself: title(title)
有没有办法在同一个字段中使用 when
?
看看在这种情况下使用 .alternatives()
rather than .when()
。 .when()
当键的值依赖于同一对象中另一个键的值时更好用。在您的情况下,我们只需要担心一把钥匙。
使用 .alternatives()
的可能解决方案如下所示:
Joi.object().keys({
title: Joi.alternatives(
Joi.string(),
Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
})
).required()
})
我正在尝试验证 POST 请求,其中 title
可以是 String 或 Object 与语言键和值。示例:
{
title: 'Chicken',
...
}
//OR
{
title: {
en_US: 'Chicken',
de_DE: 'Hähnchen'
}
...
}
对于 Joi,我正在尝试像这样验证:
{
title: Joi.any().when('title', {
is: Joi.string(),
then: Joi.string().required(),
otherwise: Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
}).required()
}),
...
}
但是,当我尝试验证时出现错误 AssertionError [ERR_ASSERTION]: Item cannot come after itself: title(title)
有没有办法在同一个字段中使用 when
?
看看在这种情况下使用 .alternatives()
rather than .when()
。 .when()
当键的值依赖于同一对象中另一个键的值时更好用。在您的情况下,我们只需要担心一把钥匙。
使用 .alternatives()
的可能解决方案如下所示:
Joi.object().keys({
title: Joi.alternatives(
Joi.string(),
Joi.object().keys({
en_US: Joi.string().required(),
lt_LT: Joi.string()
})
).required()
})