Reputation: 10564
I am trying to validate a key in json object which should have value greater than another key's value. As exception I want to allow -1
also to be valid value.
// 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'))
})
This schema is handling all case well except the exceptional case. how can I enhance my schema
to cover exceptional case also.
Upvotes: 0
Views: 462
Reputation: 18919
Just add allow(-1)
to your max schema to allow the -1 value.
var schema = Joi.object({
min: Joi.number().integer(),
max: Joi.number().integer().allow(-1).greater(Joi.ref('min'))
});
Tests:
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);
Upvotes: 1