使用Joi,要求两个字段之一不能为空 [英] Using Joi, require one of two fields to be non empty

查看:452
本文介绍了使用Joi,要求两个字段之一不能为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有两个字段,我只想验证至少一个字段是一个非空字符串,但是当两个字段都是空字符串时都会失败.

If I have two fields, I'd just like to validate when at least one field is a non empty string, but fail when both fields are empty strings.

类似的事情无法验证

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

根据进行验证

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

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

The or condition only tests for the presence of either key a or b, but does test whether the condition for a or b is true. Joi.string() will fail for empty strings.

这里有一些测试用例可以证明

Here is gist with some test cases to demonstrate

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

推荐答案

以下代码对我有用.我使用替代方法是因为.or实际上正在测试密钥的存在性,而您真正想要的是一种替代方法,其中您允许一个密钥或另一个密钥为空.

Code below worked for me. I used alternatives because .or is really testing for the existence of keys and what you really wanted was an alternative where you would allow one key or the other to be empty.

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,要求两个字段之一不能为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆