Allow optional parameters in Joi without specifying them

João Minhós Rodrigues picture João Minhós Rodrigues · Nov 4, 2015 · Viewed 10.2k times · Source

I'm fairly new to using Joi to validate request payloads in hapi. My question is the following. I have this defined route:

{
    method: 'POST',
    path: '/foo/bar',
    config: {
      description: 'foo.bar',
      handler: handlers.foo,
      auth:false,
      tags: ['api'],
      validate: {
        payload: {
          email : Joi.string().required(),
          password : Joi.string().required(),
        }
      }
    }
}

Email and password are my required properties. However, i would like to allow other properties without having to specify them all. for example:

{
  email: [email protected],
  password: fooPass,
  name: myName,
  surname: mySurname
}

Is there a way to do it with Joi?

Answer

Gergo Erdosi picture Gergo Erdosi · Nov 4, 2015

You can set allowUnknown to true in options:

validate: {
  payload: {
    email : Joi.string().required(),
    password : Joi.string().required(),
  },
  options: {
    allowUnknown: true
  }
}

The options parameter is passed to Joi on validation.