如何在 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'))
});

参考文档

测试:

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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章