如果我有两个字段,我只想验证至少一个字段是一个非空字符串,但是当两个字段都是空字符串时都会失败.
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条件仅测试键a或b的存在,但会测试a或b的条件是否为真. 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
requirebin/?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,要求两个字段之一不能为空
发布评论