0

I created a Hapi API which only allows multipart/form-data because I need to pass an image stream and one of the payloads is required as an array, so I use Joi.array to validate it.

  payload: {
    parse: true,
    maxBytes: 20971520,
    output: "stream",
    timeout: 300000,
    multipart: true,
  },
  validate: {
    payload: Joi.object({
      thumbnail: Joi.any().optional().meta({ swaggerType: "file" }),
      tags: Joi.array()
    }),
  }

In Front End side, I try to append FormData by stringify it as below:

  const formData = new FormData();

  formData.append("tags", JSON.stringify(values[val]);

But, it still showing ""tags" must be an array" error message. Is there any other way to pass an array into a form data?

1 Answers1

0

I've had the exact same issue. I'm using express, but I suppose you will find the answer helpful in Hapi as well.

You cannot directly pass the tags input to Joi validation, because it is a string representation of an array. You can first parse it -

let parsedTags = [];
if (tags) {
  parsedTags = JSON.parse(tags);
}

(this logic can be wrapped inside a try-catch to catch any parsing issue)

Then, pass parsedTags into the validation function (keeping the key as 'tags').

I don't know of any other way to do this, and this solution worked for me.

Rvy Pandey
  • 1,654
  • 3
  • 16
  • 22