I need to create dynamic schema to validate my api request query in node js
using Joi validator depending on a key in the request query. Say the following below mentioned pattern are my valid queries.
I'm using hapi/joi
version 16.1.8
Combination 1
{ type: 1, firstname: 'user first name', lastname: 'user last name'}
Combination 2
{ type: 2 , salary: 1000, pension: 200}
Combination 3
{ type: 3 , credit: 550, debit: 100}
As you can see the object keys varies depending on the value of type
. How this can be handled properly?
We can handle two conditions using Joi.alternatives like
const schema = Joi.alternatives().conditional(Joi.object({ type: 1 }).unknown(), {
then: Joi.object({
type: Joi.string(),
firstname: Joi.string(),
lastname: Joi.string()
}),
otherwise: Joi.object({
type: Joi.number(),
salary: Joi.any(),
pension: Joi.any()
})
});
But how this can be done for 3 conditions?
Joi.alternatives()
– Pulmotor