简体   繁体   English

Joi 验证:有没有办法在一个 go 中允许多个模式对象的未知键

[英]Joi Validation: Is there a way to allow unknown keys for several schema objects in one go

I have several validator files containing close to a hundred schema objects.我有几个包含近百个模式对象的验证器文件。 I'd like to validate unknown keys for all of them at the same time.我想同时验证所有这些未知密钥。 I have already figured out a way to validate unknown keys for one object which I have posted below.我已经想出了一种方法来验证我在下面发布的一个 object 的未知密钥。 Is there a way to do it for all in one go?有没有办法在一个 go 中做到这一点? I'm looking for a DRY way to do this.我正在寻找一种干燥的方式来做到这一点。

const schema = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
}).unknown(true);

// or
const schema = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
}).options({ allowUnknown: true })

You can use .defaults to create your own custom joi which in this case will have allowUnkown set true as default:您可以使用.defaults创建您自己的自定义 joi,在这种情况下将 allowUnkown 设置为默认值:

// Create your custom Joi
const customJoi = Joi.defaults((schema) => schema.options({
  allowUnknown: true 
}));

// schema using original Joi
const schema1 = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
})

// schema using custom Joi
const schema2 = customJoi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
})
 
// INVALID, "c" is not allowd
schema1.validate({ a: "a", b: "b", c: 10 })
// VALID
schema2.validate({ a: "a", b: "b", c: 10 })

This also works:这也有效:

var Joi = require("joi").defaults((schema) => schema.options({
  allowUnknown: true 
}));

or或者

var Joi = require("joi")
Joi = Joi.defaults((schema) => schema.options({
  allowUnknown: true 
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM