I seem to hit a roadblock when it comes to joi's .or() function as it doesn't seem to implement as I'd expect.
I have 2 text input fields, both have their own way of validating, though only at least one is required.
const schema = joi
.object({
"either-this-field": joi.string().trim().max(26),
"or-this-field": joi
.string()
.trim()
.regex(/^\d $/)
.max(26)
"other-field-1": joi.string().required(),
"other-field-2": joi.string().max(40).required(),
})
.or("either-this-field", "or-this-field");
it just seems that this or doesn't do as I'd expect and each field from the or is just validated as per it's own validation rules
if neither field has values, then I'll display error for both fields until at least one is completed
CodePudding user response:
Joi or
means that one or more of either-this-field
and or-this-field
should appear in the object. Appear is different than validate here.
You can omit one of the properties, but whenever you provide a value it has to match the validation rule.
It makes sense: when someone provides a bad value, you probably want to throw an error instead of swallowing the bad data silently even if it's optional.
CodePudding user response:
var schema = Joi.alternatives().try(
Joi.object().keys({
a: Joi.string().allow(''),
b: Joi.string()
}),
Joi.object().keys({
a: Joi.string(),
b: Joi.string().allow('')
})
);
alternatives().try()
adds an alternative schema type for attempting to match against the validated value. You are passing two options and it will choose one of them.