10

I need to validate an array to check if it's elements are strings using joi. It always sends the error of "Inavlid tag".

// returned array from req.body
let tags = ["Vue", "React", "Angular"]

// joi shema
const schema = {
     tags: Joi.array().items(Joi.string()),
};

const { error, value } = Joi.validate(tags, schema);

if (error) {
     return res.status(400).send({ tagError: "Invalid tag" });
}
ImInYourCode
  • 567
  • 1
  • 7
  • 19
  • BTW if you want a friendly way to return errors in an API https://github.com/hapijs/boom/blob/master/API.md I use it very often within the hapi ecosystem – Borja Tur May 30 '19 at 14:03

2 Answers2

16

Joi was recently changed to @hapi/joi (literally 2 weeks ago), so make sure first and foremost that you've switched out the NPM package properly:npm uninstall joi and npm i -s @hapi/joi. Make sure to change your require statements for this change, also.

To define your schema in this new package, you would use:

const schema = Joi.array().items(Joi.string());
Len Joseph
  • 1,406
  • 10
  • 21
-1

The issue is due to how you defined the schema, the right way to validate would be:

// returned array from req.body
let tags = ["Vue", "React", "Angular"]

const schema = Joi.array().items(Joi.string());

const { error, value } = Joi.validate(tags, schema);
Borja Tur
  • 779
  • 1
  • 6
  • 20