When using Joi with Hapi, how to configure one of them to one key, but allow any other keys?

I am trying to write a Joi check for a JSON object included in a Hapi handler. So far, the code looks like this:

server.route({ method: 'POST', path: '/converge', handler: function (request, reply) { consociator.consociate(request.payload) .then (function (result) { reply (200, result); }); }, config: { validate: { payload: { value: Joi.object().required().keys({ knownid: Joi.object() }) } } } }); 

You can see the Joi object validation so far in the config: validate: code section above. The JSON arrival is as follows.

 "key": '06e5140d-fa4e-4758-8d9d-e707bd19880d-testA', "value": { "ids_lot_args": { "this_id": "stuff", "otherThign": "more data" }, "peripheral_data": 'Sample peripheral data of any sort' } 

In this JSON above the key and value in the root of the object is required, and a section called ids_lot_args . The section that starts with files_admin can be there or not, or it can be any other JSON payload. It does not matter, only the key and value at the root level and ids_lot_args inside the value are ids_lot_args .

So far I am stumbling trying to get Joy validation to work. Any ideas on how this should be configured? The code repository for Joi is at https://github.com/hapijs/joi if you want to check it out. I tried to allow all functions on objects so far.

+8
json javascript validation hapijs
source share
3 answers

You just need to call the unknown() function of the value object:

 var schema = Joi.object({ key: Joi.string().required(), value: Joi.object({ ids_lot_args: Joi.object().required() }).unknown().required() }); 
+7
source share

You can use the "allowUnknown" parameter:

 validate : { options : { allowUnknown: true }, headers : { ... }, params : { ... }, payload : { ... } } 

}

+3
source share

Try using Joi.any ()

 server.route({ method: 'POST', path: '/converge', handler: function (request, reply) { consociator.consociate(request.payload) .then (function (result) { reply (200, result); }); }, config: { validate: { payload: { key: Joi.string().required(), value: Joi.object({ ids_lot_args: Joi.object().required(), peripheral_data: Joi.any() }) } } }}); 
+1
source share

All Articles