javascript 使用 Joi,要求两个字段之一为非空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28864812/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Joi, require one of two fields to be non empty
提问by Brendan
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.
如果我有两个字段,我只想在至少一个字段是非空字符串时进行验证,但在两个字段都是空字符串时验证失败。
Something like this does not validate
像这样的东西无法验证
var schema = Joi.object().keys({
a: Joi.string(),
b: Joi.string()
}).or('a', 'b');
When validating against
验证时
{a: 'aa', b: ''}
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.
该or
条件仅测试键a
or的存在b
,但会测试a
or的条件是否b
为真。Joi.string()
对于空字符串将失败。
Here is gist with some test cases to demonstrate
这里是一些测试用例的要点来演示
回答by Kevin Wu
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.
下面的代码对我有用。我使用了替代方案,因为 .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']);
}
回答by t k
An alternative way of using Joi.when() that worked for me:
对我有用的使用 Joi.when() 的另一种方法:
var schema = Joi.object().keys({
a: Joi.string().allow(''),
b: Joi.when('a', { is: '', then: Joi.string(), otherwise: Joi.string().allow('') })
})
回答by Tomty
If you want to express the dependency between 2 fields without having to repeat all other parts of the object, you could use when:
如果您想表达 2 个字段之间的依赖关系而不必重复对象的所有其他部分,您可以使用when:
var schema = Joi.object().keys({
a: Joi.string().allow(''),
b: Joi.string().allow('').when('a', { is: '', then: Joi.string() })
}).or('a', 'b');