joi icon indicating copy to clipboard operation
joi copied to clipboard

Getting all possible validation errors for a given schema

Open KKSzymanowski opened this issue 2 years ago • 3 comments
trafficstars

Support plan

  • is this issue currently blocking your project? (yes/no): no
  • is this issue affecting a production system? (yes/no): no

Context

  • node version: 18
  • module version: 17.6
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): standalone

How can we help?

Given some schema, how can I list all possible validation errors that can occur when validating an object against that schema.

For example for this schema:

Joi.object({
  foo: Joi.string().required().max(255),
  bar: Joi.object({
    baz: Joi.boolean(),
    qux: Joi.number(),
  }).required().xor('baz', 'qux')
})

I'd get:

.           object.base
.foo        any.required
.foo        string.empty
.foo        string.base
.foo        string.max
.bar        any.required
.bar        object.xor(baz,qux)
.bar        object.base
.bar.baz    boolean.base
.bar.qux    number.base

KKSzymanowski avatar Apr 04 '23 18:04 KKSzymanowski

It might not give you the exact output you're looking for but you might be able to reconstruct it yourself, have you looked into: schema.describe()?

https://joi.dev/api/?v=17.9.1#anydescribe

Nargonath avatar Apr 05 '23 06:04 Nargonath

Sadly describe() doesn't give any validation error messages and the info it gives isn't really structured in a way to be easily translated into the messages.

I have tried doing it via schema.$_terms but I can't ever be sure that I'm including everything because some rules are under dependencies, some are under flags etc. Also the messages don't align very well with the rules in some cases, for example { presence: 'forbidden' } generates any.unknown, not any.forbidden.

KKSzymanowski avatar Apr 05 '23 14:04 KKSzymanowski

Alright I understand. Maybe somebody else has a better suggestion for you.

Nargonath avatar Apr 06 '23 07:04 Nargonath