Our use case means that:
Joi works great, but because of our requirements it becomes much more verbose that it needs to be and more importantly more error prone.
Im considering writing a simple wrapper around joi that would ensure that required is set to true and unknown set to false by default.
However before I do I'd like to know if this is something we would want to or should do in the core library?
Looking forward to some feedback! Cheers! L~
You can absolutely do this with Joi, as-is! Check out .defaults():
const BaseJoi = require('joi');
const Joi = BaseJoi.defaults((schema) => schema.options({
presence: 'required',
allowUnknown: false
}));
// missing base value
Joi.string().validate(); // ValidationError: "value" is required
// unknown key
Joi.object().keys({}).validate({a: 'thing'}); // ValidationError: "a" is not allowed
// missing key
Joi.object().keys({
a: Joi.string()
}).validate({}); // ValidationError: child "a" fails because ["a" is required]
// nested object with missing key
Joi.object().keys({
a: Joi.object().keys({
b: Joi.string()
})
}).validate({a: {}}); // ValidationError: child "a" fails because [child "b" fails because ["b" is required]]
// nested object with a specifically optional key
Joi.object().keys({
a: Joi.object().keys({
b: Joi.string().optional()
})
}).validate({a: {}}); // error: null
I had absolutely no idea! This is great news!
Thank you very much for the informative examples as well!
Closing as this is now fully resolved to my satisfaction
Not allowing unknown keys is already the default fwiw. You could just set .options({ presence: 'required' }) on your root schemas and that'd do, I think.
Just published this under https://github.com/blackflux/joi-strict
Thank you for your input!
This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.
Most helpful comment
Not allowing unknown keys is already the default fwiw. You could just set
.options({ presence: 'required' })on your root schemas and that'd do, I think.