Arkanoid
Arkanoid

Reputation: 1195

Validating an array's length against another array's length using joi

Is there a way to validate that two arrays need to have the same length using joi?

Here's an example:

Joi.object().keys({
  firstNames: Joi.array().items(Joi.string()).single(),
  lastNames: Joi.array().items(Joi.string()).single(),
});

If that was to work, it should also match both array's length so no firstName lacks a lastName.

Thanks for the help!

Upvotes: 4

Views: 2188

Answers (2)

Alex
Alex

Reputation: 3855

The docs for array.length(limit) allude to this:

Joi.object().keys({
  firstNames: Joi.array().items(Joi.string()).single(),
  lastNames: Joi.array()
    .items(Joi.string())
    .single()
    .length(Joi.ref('firstNames.length')),
});

Upvotes: 0

Ankh
Ankh

Reputation: 5738

There certainly is, take a look at .assert(). You can use it to compare the values or attributes of two properties in your object.

For your example you can do this:

Joi.object().keys({
  firstNames: Joi.array().items(Joi.string()).single(),
  lastNames: Joi.array().items(Joi.string()).single(),
}).assert('firstNames.length', Joi.ref('lastNames.length'));

You can also optionally provide a more helpful error message as the third parameter of .assert().

Upvotes: 5

Related Questions