2
votes

I want to allow my front-end to push a hash of values to the backend. The hash can have any (JSON-legal) key, but the value of each key has to fit a specific schema. Think of it like:

extended: {
  tubers: {
    potato: {weight: 1, cost: 2},
    yam: {weight: 1, cost: 1}
  }
}

So the extended object has a tubers field. The tubers field has many keys, but each value has to have a weight and a cost which are integers.

I can't quite seem to map that into my normal Joi object schema framework.

1

1 Answers

5
votes

You can use Joi.object().pattern() to validate unknown keys:

var schema = {
    extended: {
        tubers: Joi.object().pattern(/^\w+$/, Joi.object().keys({
            weight: Joi.number().required(),
            cost: Joi.number().required()
        }).unknown())
    }
};

If you don't want to allow other keys than weight and cost, then remove .unknown().