Joi: Adding more restrictive joi "variant"

Created on 15 May 2019  路  5Comments  路  Source: sideway/joi

Our use case means that:

  • almost everything is required
  • there are never any unknown keys allowed in objects

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~

support

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.

All 5 comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alekbarszczewski picture alekbarszczewski  路  3Comments

longweiquan picture longweiquan  路  3Comments

leore picture leore  路  4Comments

Taxi4you picture Taxi4you  路  3Comments

n-sviridenko picture n-sviridenko  路  3Comments