Joi "or" 运算符认为空字符串是有效输入

Joi "or" operator thinks an empty string is a valid input

我正在尝试在 Joi ver.17.4.0 中使用“或”运算符

如您所见,在下面的代码中,我希望 attributes/properties 中的一个或两个都被允许,但不能两者都不被允许。

问题是 Joi 不允许字符串为空。因此,要将其清空,我需要:

Joi.string().allow('')

根据“或”运算符,这使其不为空。所以我不能让“或”眼中的'name'为空。

它无法正确验证。 即使我这样做它也会验证(但它不应该):

validatePerson(createPerson(''));

请记住,我实际上是在验证节点表达式 API 上的 POST 输入,因此这是一些用于说明问题的简化代码:

const Joi = require('Joi');

function createPerson(name, age) {
  const person = { name: name, age: age };
  console.log(person);
  return person;
}

function validatePerson(person) {
  const schema = Joi.object({
    name: Joi.string().allow(''),
    age: Joi.number(),
  }).or("name", "age");
  console.log(schema.validate(person));
  return schema.validate(person);
}


validatePerson(createPerson('')); // This should fail validation but doesn't
validatePerson(createPerson()); // Should fail and does
validatePerson(createPerson('Bob')); // Should pass and does
validatePerson(createPerson('', 7)); // Should pass and does
validatePerson(createPerson('Bob', 7)); // Should pass and does

据我了解,您希望 name 为空字符串,前提是 age 存在。

为此,您可以使用 .when:

name: Joi.string().when('age', { is: Joi.exist(), then: Joi.allow('') })

这样,您的第一个示例将如您预期的那样失败。