Joi array reducer?

349 Views Asked by At

I have an array of Joi strings:

const item = Joi.string().max(50)
const items = Joi.array().items(item).max(20)

Each individual item can be a max of 50 chars, and there are a max of 20 items.

So far so good, however...

I also have to verify that the combined length of all of the strings in the array does not exceed 200 chars in total.

Is it possible purely in Joi?

1

There are 1 best solutions below

1
On BEST ANSWER

It looks like you can use the any.custom method and pass you custom validation logic.

Based on that documentation we first we need to create a function for validating the array of strings that accepts two args, the "value" and a "helpers" object.

const contentsLength = (value, helpers) => {
  // do a map reduce to calculate the total length of strings in the array
  const len = value.map((v) => v.length).reduce((acc, curr) => acc + curr, 0);

  // make sure that then length doesn't exceed 20, if it does return an error using
  // the message method on the helpers object 
  if (len > 200) {
    return helpers.message(
      "the contents of the array must not exceed 200 characters"
    );
  }

  // otherwise return the array since it's valid
  return value;
};

Now add it to your items schema

const items = Joi.array().items(item).max(20).custom(contentsLength);

You can check out the code here with an example using a valid and invalid array: https://codesandbox.io/s/gallant-ptolemy-k7h5i?file=/src/index.js