I have a field in a JOI schema that I would like to be optional (i.e. undefined is accepted, and null is also accepted), however if a value for it is supplied, it must be a positive integer. How might I go about achieving this?
Here is what I have tried so far, with the field to validate being "capacity" however it does not seem to work, it appears the ".when" statement is just being ignored:
const divebarSchema = joi.object({
divebar: joi
.object({
title: joi.string().required(),
capacity: joi.optional().allow(null),
description: joi.string().required(),
location: joi.string().required(),
image: joi.string().optional().allow(""),
map: joi.string().optional().allow(""),
})
.required()
.when(joi.object({ capacity: joi.exist() }), {
then: joi.object({ capacity: joi.number().integer().min(0) }),
}),
});
Before the above I originally had no .when and instead the capacity rule was:
capacity: joi.number().optional().allow(null).integer().min(0),
However that also did not work, it kept throwing the error "must be a number" when submitting a null value.
capacity: joi.integer().min(0)
in the original object? – Deflectioncapacity: joi.integer().min(0)
doesn't work as I believe .integer only works on joi.number. However capacity:joi.number().integer().min(0)
isn't what I am looking for as that would not allow a null value. I already tried adding theallow(null)
rule with no luck - I updated my question description to explain what I tried beforehand. – Trangtranquada.while
is being ignored. Also, removing.required
is not what I want to do as I would like the overall object to be mandatory in the incoming request. – Trangtranquada