Skip to content

Joi.object().xor() throws with "must be a string or a reference" when passed a reference #2471

@cdhowie

Description

@cdhowie

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: 12.18.3
  • module version with issue: 17.2.1
  • last module version without issue: Unknown, have not yet tried prior versions
  • environment (e.g. node, browser, native): Node
  • used with (e.g. hapi application, another framework, standalone, ...): Standalone
  • any other relevant information: N/A

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

I am trying to make a schema that will validate an object with any key (Joi.object().pattern(/./, valueSchema)) but where a specific key is required, but which key comes from the object being validated. For example:

const schema = Joi.object().keys({
  defaultTag: Joi.string().required(),
  tags: Joi.object().required().pattern(/./, Joi.object().required()),
});

However, requiring value.tags[value.defaultTag] to be present. There doesn't seem to be a built-in way to accomplish this; I can't find a way to use a ref as an object key. (An API like Joi.object().key(Joi.ref('foo'), Joi.number().required()), for example, would permit this, but I can't find anything like this. Anyway, this is beside the point.)

The simplest approach seemed to be to (ab)use .xor() by giving it a single ref (Joi.ref('defaultTag')). However, the .xor() call results in a confusing/contradictory exception. It boils down to this:

Welcome to Node.js v12.18.3.
Type ".help" for more information.
> const Joi = require('joi');
undefined
> Joi.object().xor(Joi.ref('foo'));
Uncaught Error: xor peers must be a string or a reference

What was the result you got?

Uncaught Error: xor peers must be a string or a reference

What result did you expect?

Either .xor() should accept a reference, or the error message should not indicate that a reference is acceptable.

Metadata

Metadata

Assignees

Labels

bugBug or defect

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions