joi icon indicating copy to clipboard operation
joi copied to clipboard

Does joi have a short circuiting "and" mechanism?

Open williamblevins opened this issue 2 years ago • 1 comments

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: v14.17.5
  • module version: 17.4.2 (tried other versions also)
  • environment (e.g. node, browser, native): node
  • used with (e.g. hapi application, another framework, standalone, ...): N/A
  • any other relevant information: N/A

How can we help?

Is there a cleaner way to do a short circuiting "and" validation? What I really want to do is, if not joi.string().required() fail; otherwise, also check joi.valid('tag').error(new SoftValidationError('<insert message here>')). This allows for a custom error if-and-only-if the prerequisites hold.

joi.when({ is: joi.string().required(), then: joi.valid('tag').error(new SoftValidationError('<insert message here>')), otherwise: joi.string().required() })

williamblevins avatar Sep 13 '21 17:09 williamblevins

Can you clarify the following: After the prerequisites passes, are you trying to throw a custom error or throw a custom error message?

If your answer is the latter, then the following will work for you:

const schema = joi.string()
.valid('tag') //only the string 'tag' is valid
.required() // value must not be undefined
.messages({'any.only':'The only allowed string is "tag"!'}) //if 'valid' validation failed, throw this specific error message

schema.validateAsync('hello') // will throw error message: "ValidationError: The only allowed string is \"tag\"!"

schema.validateAsync() // will throw error message "ValidationError: "value" is required"

Kanosakl avatar Dec 03 '21 04:12 Kanosakl