Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  54] [ 2]  / answers: 1 / hits: 27390  / 9 Years ago, wed, march 4, 2015, 12:00:00

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.



Here is gist with some test cases to demonstrate



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


More From » hapi.js

 Answers
29

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']);
}

[#67566] Tuesday, March 3, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tai

Total Points: 466
Total Questions: 87
Total Answers: 116

Location: Saint Helena
Member since Tue, Nov 3, 2020
4 Years ago
;