使用Join,要求两个字段中的一个字段为非空

Using Joi, require one of two fields to be non empty

本文关键字:字段 一个 Join 使用 两个      更新时间:2023-09-26

如果我有两个字段,我只想在至少一个字段是非空字符串时进行验证,但在两个字段都是空字符串时失败。

像这样的东西不能验证

var schema = Joi.object().keys({
    a: Joi.string(),
    b: Joi.string()
}).or('a', 'b');

根据进行验证时

{a: 'aa', b: ''}

or条件仅测试密钥ab的存在,但确实测试ab的条件是否为真。对于空字符串,Joi.string()将失败。

以下是演示的一些测试用例的要点

http://requirebin.com/?gist=84c49d8b81025ce68cfb

下面的代码对我很有用。我使用替代方案是因为.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']);
}

另一种对我有用的使用Joi.when()的方法:

var schema = Joi.object().keys({
  a: Joi.string().allow(''),
  b: Joi.when('a', { is: '', then: Joi.string(), otherwise: Joi.string().allow('') })
}).or('a', 'b')

.or('a', 'b')防止ab为空(与"相反)。

如果您想在不必重复对象的所有其他部分的情况下表达2个字段之间的依赖关系,可以使用when:

var schema = Joi.object().keys({
  a: Joi.string().allow(''),
  b: Joi.string().allow('').when('a', { is: '', then: Joi.string() })
}).or('a', 'b');

您可以使用.xor('a', 'b')而不是.or('a', 'b'):

var schema = Joi.object().keys({
    a: Joi.string(),
    b: Joi.string()
}).xor('a', 'b');

这允许是或仅a仅b不同时,且不能无

if your object is:
{ a: 'non-empty' } or { b: 'non-empty' }
will pass
if your object is:
{ a: '', b: '' } or { a: 'non-empty', b: 'non-empty' } 
will NOT pass
if your object is:
{ a: ''} or { b: '' } 
will NOT pass
if your object is:
{ a: '', b: 'non-empty' } or { a: 'non-empty', b: '' } 
will NOT pass
if your object is:
{ }
will NOT pass

我面临的问题https://stackoverflow.com/a/61212051/15265372答案是,若同时给出这两个字段,你们就不会面临任何错误,若你们想解决这个问题,你们需要用xor替换or

&。你可以简单地使用'.and()'

  • 如果其中任何一个字段为空,它都不会通过
var schema = Joi.object().keys({
   a: Joi.string(),
   b: Joi.string()
}).and('a', 'b');````
相关文章: