Joi для проверки альтернатив в зависимости от нескольких ключей

Используя Joi, как заставить схему требовать rent.max только тогда, когда type либо A, либо B И subType равно либо AA, либо BB? Вот моя попытка.

const Joi = require("joi");
const schema = Joi.object().keys({
  type: Joi.string().valid('A', 'B', 'C').required(),
  subType: Joi.string().valid('AA', 'BB', 'X'),
  rent: Joi.object().keys({
    price: Joi.number().required().precision(2),
    // max is allowed only when type is A or B
    // and subType is AA or BB.
    max: Joi.alternatives()
      .when('type', {
        is: Joi.valid('A', 'B'),
        then: Joi.alternatives().when('subType', {
            is: Joi.valid('AA', 'BB'),
            then: Joi.number(),
            otherwise: Joi.forbidden()
        }),
        otherwise: Joi.forbidden()
      })
  })
});
const obj = {
    type: 'A',
    subType: 'AA',
    rent: {
        price: 3000.25,
        max: 300.50,
    }
};
const result = Joi.validate(obj, schema);
console.log(result.error);

Я ожидаю, что проверка не удастся, но это не так.


person Duoc Tran    schedule 18.04.2019    source источник


Ответы (1)


Если вы хотите проверить ключи type и subType, ваша проверка должна происходить после объекта, например:

const schema = Joi.object({
        type: Joi.string().valid('A', 'B', 'C'),
        subType: Joi.string().valid('AA', 'BB', 'X'),
        rent: Joi.object({
            amount: Joi.number(),
            price: Joi.number().required().precision(2),
        })
    }).when(Joi.object({
        type: Joi.string().valid('A', 'B').required(),
        subType: Joi.string().valid('AA', 'BB').required()
    }).unknown(), {
        then: Joi.object({
            rent: Joi.object({
                amount: Joi.number().required()
            })
        }),
        otherwise: Joi.object({
            rent: Joi.object({
                amount: Joi.forbidden()
            })
        })
    });

Это результаты для следующих примеров:

// FAIL - requires amount
   const obj = {
        type: 'A',
        subType: 'BB',
        rent: {
            price: 10
        }
    };

// FAIL - amount is not allowed
    const obj = {
        type: 'A',
        subType: 'X',
        rent: {
            amount: 3000.25,
            price: 300.50
        }
    };


// SUCCESS
    const obj = {
        type: 'A',
        subType: 'BB',
        rent: {
            amount: 3000.25,
            price: 300.50
        }
    };

// SUCCESS
   const obj = {
        type: 'A',
        subType: 'X',
        rent: {
            price: 300.50
        }

    };
person soltex    schedule 22.04.2019