Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow optional parameters in Joi without specifying them

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?

like image 607
João Minhós Rodrigues Avatar asked Nov 03 '15 23:11

João Minhós Rodrigues


2 Answers

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.

like image 180
Gergo Erdosi Avatar answered Oct 26 '22 15:10

Gergo Erdosi


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

like image 26
harkirat1892 Avatar answered Oct 26 '22 14:10

harkirat1892