I have several validator files containing close to a hundred schema objects. I'd like to validate unknown keys for all of them at the same time. I have already figured out a way to validate unknown keys for one object which I have posted below. Is there a way to do it for all in one go? I'm looking for a DRY way to do this.
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).unknown(true);
// or
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).options({ allowUnknown: true })
I have several validator files containing close to a hundred schema objects. I'd like to validate unknown keys for all of them at the same time. I have already figured out a way to validate unknown keys for one object which I have posted below. Is there a way to do it for all in one go? I'm looking for a DRY way to do this.
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).unknown(true);
// or
const schema = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
}).options({ allowUnknown: true })
Share
asked Mar 4, 2021 at 9:18
Mohnish MMohnish M
1233 silver badges14 bronze badges
1
- But I'm not able to make API calls. I get this "\"c\" is not allowed" message without using the above rule. – Mohnish M Commented Mar 4, 2021 at 10:25
1 Answer
Reset to default 5You can use .defaults to create your own custom joi which in this case will have allowUnkown set true as default:
// Create your custom Joi
const customJoi = Joi.defaults((schema) => schema.options({
allowUnknown: true
}));
// schema using original Joi
const schema1 = Joi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
})
// schema using custom Joi
const schema2 = customJoi.object().keys({
a: Joi.string().required(),
b: Joi.string().required()
})
// INVALID, "c" is not allowd
schema1.validate({ a: "a", b: "b", c: 10 })
// VALID
schema2.validate({ a: "a", b: "b", c: 10 })
This also works:
var Joi = require("joi").defaults((schema) => schema.options({
allowUnknown: true
}));
or
var Joi = require("joi")
Joi = Joi.defaults((schema) => schema.options({
allowUnknown: true
}));