在Joi中允许可选参数而不指定它们

Joã*_*ues 7 javascript node.js hapijs joi

我很擅长使用Joi来验证hapi中的请求有效负载.我的问题如下.我有这个定义的路线:

{
    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(),
        }
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

电子邮件和密码是我要求的属性.但是,我想允许其他属性而不必全部指定它们.例如:

{
  email: foo@bar.com,
  password: fooPass,
  name: myName,
  surname: mySurname
}
Run Code Online (Sandbox Code Playgroud)

Joi有办法做到吗?

Ger*_*osi 14

您可以设置allowUnknowntrueoptions:

validate: {
  payload: {
    email : Joi.string().required(),
    password : Joi.string().required(),
  },
  options: {
    allowUnknown: true
  }
}
Run Code Online (Sandbox Code Playgroud)

options参数在验证时传递给Joi.


har*_*892 5

对于当前版本的 Joi (v15.1.0),同时执行

Joi.validate(value, schema, options)

allowUnknown: true

进入options物体。

参考

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