hapijs / joi

The most powerful data validation library for JS
Other
20.95k stars 1.51k forks source link

Getting all possible validation errors for a given schema #2937

Open KKSzymanowski opened 1 year ago

KKSzymanowski commented 1 year ago

Support plan

Context

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
Nargonath commented 1 year ago

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

KKSzymanowski commented 1 year ago

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.

Nargonath commented 1 year ago

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