Skip to content

Problem with multiple when and conditional forbidden field #822

@bitcloud

Description

@bitcloud

I currently try to implement a validation where the existence or validation of an attribute in an object is dependent on another attribute.

I tried with a chain of any.when():

const Joi = require('joi');
const schemaWhen = Joi.object().keys({
    a: Joi.string().valid('1','2').required(),
    b: Joi
        .when('a', {is: '1', then: Joi.forbidden() })
        .when('a', {is: '2', then: Joi.number().integer().min(1).max(5).required() })
});

Joi.assert({a: '1'}, schemaWhen); // Pass
Joi.assert({a: '1', b: 50}, schemaWhen); // Fail
Joi.assert({a: '2', b: 5}, schemaWhen); // Pass
Joi.assert({a: '2', b: 50}, schemaWhen); // Pass. But should Fail?

... and with alternative:

const Joi = require('joi');
const schemaAlternative = {
    a: Joi.string().valid('aa','ab', 'ac').required(),
    b: Joi.alternatives()
        .when('a', {is: 'aa', then: Joi.string().valid('ba', 'bb').required()})
        .when('a', {is: 'ab', then: Joi.string().valid('bc').required()})
        .when('a', {is: 'ac', then: Joi.forbidden()})
};


Joi.assert({ a: 'aa', b: 'ba' }, schemaAlternative); // Pass
Joi.assert({ a: 'aa', b: 'bb' }, schemaAlternative); // Pass
Joi.assert({ a: 'ab', b: 'bc' }, schemaAlternative); // Pass
Joi.assert({ a: 'ac' }, schemaAlternative); // Pass

Joi.assert({ a: 'aa', b: 'bc' }, schemaAlternative); // Fail
Joi.assert({ a: 'ab', b: 'ba' }, schemaAlternative); // Fail
Joi.assert({ a: 'ac', b: 'ba' }, schemaAlternative); // Fail

Joi.assert({ a: 'aa' }, schemaAlternative); // Pass. But should Fail?
Joi.assert({ a: 'ab' }, schemaAlternative); // Pass. But should Fail?

..., but had no luck so far.

I even think the result should be considered a bug, or am I missing something?

Metadata

Metadata

Assignees

Labels

breaking changesChange that can breaking existing codebugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions