12

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: foo@bar.com,
  password: fooPass,
  name: myName,
  surname: mySurname
}

Is there a way to do it with Joi?

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94

2 Answers2

31

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.

Gergo Erdosi
  • 40,904
  • 21
  • 118
  • 94
5

For current version of Joi (v15.1.0), while doing

Joi.validate(value, schema, options)

set allowUnknown: true

into the options object.

Reference:

https://github.com/hapijs/joi/blob/v15.1.0/API.md#validatevalue-schema-options-callback

harkirat1892
  • 453
  • 5
  • 19