Joi: Support to validate Payload which can be a single object or array of objects.

Created on 9 Jan 2017  路  4Comments  路  Source: sideway/joi

Context

  • v6.9.1:
  • 7.3.0:
  • node :
  • hapi :
  • validating payload by defining schema in config object in routes file:

What are you trying to achieve or the steps to reproduce ?

I have a route [POST] on my api server which is used for storing data in db . Client has the flexibility to pass the payload as the single js object or array of js objects and rest part is handled on server side.

// sample payload are: 
 {
    "label": "AuthToken",
    "key": "authtoken",
    "placeholder": "AuthToken",
    "help_text":"authtoken"
 }

 // or

[
 {
    "label": "AuthToken",
    "key": "authtoken",
    "placeholder": "AuthToken",
    "help_text":"authtoken"
 },
 {
    "label": "Secret",
    "key": "secret",
    "placeholder": "Secret",
    "help_text":"secret"
 }
]

 // routes.js

module.exports = [
{ path: '/api/saveFields', method: 'POST', config: {validate:{ payload:  Schemas.customSchema }, handler: handlerJS }  }
]

Currently there is no such feature to validate if it is array or validate if it is single object . I have put all my validation schemas in separate files and used in this route files rather than in my handler.

support

All 4 comments

Currently there is no such feature to validate if it is array or validate if it is single object

Did you try Joi.alternatives()?

This feature exists, it's Joi.array().single().

hmm would the intent of that not be clearer as allowSingle or something?
And the result is always an array right?

I'm trying to keep names short. The result will always be an array yes, I guess that's a difference with the alternatives solution.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

builtbybrayne picture builtbybrayne  路  4Comments

mohamadresaaa picture mohamadresaaa  路  3Comments

REBELinBLUE picture REBELinBLUE  路  3Comments

kevbook picture kevbook  路  4Comments

a-c-m picture a-c-m  路  3Comments