Joi: How to validate hashmaps?

Created on 6 Sep 2017  路  3Comments  路  Source: sideway/joi

Sorry this is probably a really stupid question but I just can't figure it out and can't find the answer on stackoverflow or by googling.

My request is a JSON object where the keys are IDs (therefore completely dynamic) but the values of said keys is a specific object, so for instance

{
   "an-id": {
     "name": "John",
     "email": "[email protected]"
   },
   "another-id": {
     "name": "Paul",
     "email": "[email protected]"
   }
}

Obviously if it were an array of objects it'll just be

const objectSchema = Joi.object().keys({
  name: Joi.string().required(),
  email: Joi.string().email().required(),
});

const usersArray = Joi.array().items(objectSchema).required();

so I thought maybe something like Joi.object().items(objectSchema).required() but obviously that doesn't work.

I assume this is very doable and I'm just being really stupid.

support

Most helpful comment

I think you want something like

Joi.object().pattern(/\w/, Joi.object().keys({
    name: Joi.string(),
  email: Joi.string().email()
}))

The patterns basically states that for the top object any key must match \w (which is just any word) and the value of that key must be the schema
see https://github.com/hapijs/joi/blob/master/API.md#objectpatternregex-schema

All 3 comments

I think you want something like

Joi.object().pattern(/\w/, Joi.object().keys({
    name: Joi.string(),
  email: Joi.string().email()
}))

The patterns basically states that for the top object any key must match \w (which is just any word) and the value of that key must be the schema
see https://github.com/hapijs/joi/blob/master/API.md#objectpatternregex-schema

Ah! That makes perfect sense, I missed that one. Thanks. 馃憤

Np glad I could help!

Was this page helpful?
0 / 5 - 0 ratings