Skip to content

Ref inside top-level array items/ordered #1702

@hbarcelos

Description

@hbarcelos

Problem

Since Javascript doesn't have a Tuple type, usually we represent tuples as "fixed"-size arrays.
Imagine that I want a sorted pair validation.

I could do something like:

const sortedPair = Joi.array().ordered([
    Joi.number().required(),
    Joi.number().min(Joi.ref('0')).required(),
]).required();

However, this doesn't work, because if I run:

Joi.validate([1, 2], sortedPair);

I get:

ValidationError: "value" at position 1 fails because ["1" references "0" which is not a number]

Interestingly, currently it's possible to achieve this behavior if:

  1. I transform sortedPair into an object:

    const sortedPairObj = Joi.object().keys({
        low: Joi.number().required(),
        high: Joi.number().min(Joi.ref('low')).required(),
    }).required();
  2. I wrap sortedPair into an object:

    const schema = Joi.object().keys({
      sortedPair: Joi.array()
        .ordered([
          Joi.number().required(),
          Joi.number()
            .min(Joi.ref('sortedPair.0'))
            .required(),
        ])
        .required(),
    });

As for 2., I also tried to do the following:

Joi.validate([1, 2], Joi.reach(schema, 'sortedPair'))

But once again I got an error:

ValidationError: "value" at position 1 fails because ["1" references "sortedPair.0" which is not a number]

Affected APIs

  • .array()
  • .ref()

Did I miss something?

If this is an actual issue, I thinks I might be able to work on a PR.

Metadata

Metadata

Assignees

Labels

featureNew functionality or improvement

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions