我正在尝试使用以下条件验证我的target
对象:
if (target.company === `GP` AND one of target.documents type equals `full`) {
one of target.documents type must equals `part-should-be-error`
} else {
throw new Error()
}
在此示例中,验证不会返回任何错误,但是由于'part' !== 'part-should-be-error'
我尝试了https://stackoverflow.com/a/53647449/10432429,但不适用于Joi v15
由于我无法将数组架构与其他架构合并,因此我所能做的就是使用$
来获取全局context
,但似乎也不起作用
我在Joi v15.1.1上具有代码库,因此请安装相同版本
npm i @hapi/joi@15.1.1
const Joi = require('@hapi/joi');
(async () => {
const target = {
name: 'Jeff',
company: 'GP',
documents: [
{type: 'full', value: 'apple'},
{type: 'part', value: 'tesla'},
],
};
const documents = Joi.object().keys({
type: Joi.string().valid(['full', 'part', 'empty']),
value: Joi.string().min(1).max(40)
.required(),
}).required();
const schema = Joi.object()
.keys({
name: Joi.string().min(1).max(20)
.required(),
company: Joi.string().valid(['GP', 'QW']),
documents: Joi.array().items(documents).min(1)
.when('$', {
is: Joi.object().keys({
company: Joi.string().valid(['GP']),
documents: Joi.array().has(Joi.object({type: Joi.string().valid('full')}).unknown().required()),
}).unknown().required(),
then: Joi.array().has(Joi.object({type: Joi.string().valid(['part-should-be-error'])}).unknown()).required(),
})
.required(),
});
await Joi.validate(target, schema, {context: target});
})();
如果我确实很奇怪,请随时显示另一种解决方法