如何让 Joi 具有非凡的价值?

How to allow exceptional value in Joi?

我正在尝试验证 json 对象中的键,该键的值应大于另一个键的值。作为例外,我想让 -1 也成为有效值。

// valid because max is greater than min
var object1 = {
    min: 5,
    max: 7
}

// invalid because max is not greater than min
var object2 = {
    min: 5,
    max: 5
}

// invalid because max is not greater than min
var object3 = {
    min: 5,
    max: 3
}

// valid as exception we want to allow -1
var object4 = {
    min: 5,
    max: -1
}

var schema = Joi.object({
    min: Joi.number().integer(),
    max: Joi.number().integer().greater(Joi.ref('min'))                   
})

除例外情况外,此架构可以很好地处理所有情况。我怎样才能增强我的 schema 以涵盖特殊情况。

只需将 allow(-1) 添加到您的最大模式以允许 -1 值。

var schema = Joi.object({
    min: Joi.number().integer(),
    max: Joi.number().integer().allow(-1).greater(Joi.ref('min'))
});

Ref Docs

测试:

const Joi = require('@hapi/joi');
const assert = require('assert');

var schema = Joi.object({
    min: Joi.number().integer(),
    max: Joi.number().integer().allow(-1).greater(Joi.ref('min'))
});

// valid because max is greater than min
var object1 = {
    min: 5,
    max: 7
};

assert.deepStrictEqual(schema.validate(object1).error, undefined);

// invalid because max is not greater than min
var object2 = {
    min: 5,
    max: 5
};

assert.notStrictEqual(schema.validate(object2).error, undefined);

// invalid because max is not greater than min
var object3 = {
    min: 5,
    max: 3
};

assert.notStrictEqual(schema.validate(object3).error, undefined);

// valid as exception we want to allow -1
var object4 = {
    min: 5,
    max: -1
};

assert.deepStrictEqual(schema.validate(object4).error, undefined);