hapijs joi validation , just validate one field and to allow any field

stackdave picture stackdave · Sep 14, 2016 · Viewed 11.4k times · Source

I want to validate one field and to allow another fields without validation; by example just to validate: "firstname" field. In my code when I comment 'payload', hapi allow me to record any field, when I uncomment 'payload' hapijs dont allow me record any field, but I want just to validate by example 'firstname' to be a 'string' and let rest of fields to allow. I plan to have variable fields accord a database config, so I'm going to just validate some fixed fields and let to save another variable fields controlled in the front end, not in the backend

  config: {
      validate: {
         /* payload: {
            firstname: Joi.string(),
            lastname: Joi.string()
            ...anothers fields...

          }*/
      }
  }

UPDATED: thanks to Robert K. Bell, i've adapted the solution is to add 'validate':

  config: {
      validate: {
         options: {
            allowUnknown: true
          },
          payload: {
            firstname: Joi.string()
          }
      }
  }

Answer

Robert K. Bell picture Robert K. Bell · Sep 15, 2016

You may be looking for the .unknown() method:

object.unknown([allow])

Overrides the handling of unknown keys for the scope of the current object only (does not apply to children) where:

  • allow - if false, unknown keys are not allowed, otherwise unknown keys are ignored.

js const schema = Joi.object({ a: Joi.any() }).unknown();