hapijs / joi

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

Conceptual documentation for ruleset and flag #2967

Open zspitz opened 1 year ago

zspitz commented 1 year ago

Context

What are you trying to achieve or the steps to reproduce ?

The following code:

import Joi from 'joi';

const schema = Joi.object({
    email: Joi.string().ruleset
        .pattern(/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.com/)
        .required()
        .rule({ message: 'Invalid email' })
        .required()
});

fails with Cannot set flag inside a ruleset.

As someone new to Joi, I was unsure how to approach this error. Searching for the error text gives no useful results (#2700, #2287). It was only after multiple passes through the API documentation that I understood:

and thus, the first call to required is causing the error, coming as it does after a reference to the ruleset.

To my knowledge, nowhere in the documentation is there a definition of what is a ruleset, or the meaning of multiple rulesets (as implied by mention of the "current ruleset").

In any.rules there is the following paragraph:

Rule modifications can only be applied to supported rules. Most of the any methods do not support rule modifications because they are implemented using schema flags (e.g. required()) or special internal implementation (e.g. valid()). In those cases, use the any.messages() method to override the error codes for the errors you want to customize.

which seems to apply. But the path from the error message to this particular paragraph is rather obscure.

I would suggest adding some kind of conceptual documentation or FAQ:

  1. What does "ruleset" mean? How can there be multiple rulesets?
  2. What are flags?
  3. I'm getting "Cannot set flag inside a ruleset". How do I fix this?