下面的代码对我有用。我使用了替代方案,因为 .or 确实在测试密钥的存在,而您真正想要的是允许一个密钥或另一个为空的替代方法。
var console = require("consoleit");
var Joi = require('joi');
var schema = Joi.alternatives().try(
Joi.object().keys({
a: Joi.string().allow(''),
b: Joi.string()
}),
Joi.object().keys({
a: Joi.string(),
b: Joi.string().allow('')
})
);
var tests = [
// both empty - should fail
{a: '', b: ''},
// one not empty - should pass but is FAILING
{a: 'aa', b: ''},
// both not empty - should pass
{a: 'aa', b: 'bb'},
// one not empty, other key missing - should pass
{a: 'aa'}
];
for(var i = 0; i < tests.length; i++) {
console.log(i, Joi.validate(tests[i], schema)['error']);
}