javascript 如何在 Joi 中允许任何其他键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49897639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:49:38  来源:igfitidea点击:

How to allow any other key in Joi

javascripthapijsjoi

提问by Anand Undavia

I have a simple requirement. I tried to search on the internet as well as documentation but failed.
So here is what I want to achieve:

我有一个简单的要求。我试图在互联网和文档上进行搜索,但失败了。
所以这就是我想要实现的目标:

I have a schema:

我有一个架构:

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

Now, How do I configure it such that any other key in the object would be allowed?

With this schema, it only allows two keys aand b. If I pass any other key, say, c, it throws an error saying that cis not allowed.

现在,如何配置它以便允许对象中的任何其他键?

使用此架构,它只允许两个键ab。如果我传递任何其他键,例如,c它会抛出一个错误,指出这c是不允许的。

采纳答案by Carsten

You can add unknown keys using object.pattern(regex, schema)this way IF you want to make sure these unknown keys are strings:

如果您想确保这些未知键是字符串您可以通过这种方式使用object.pattern(regex, schema)添加未知键:

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

For a general pass of all key types use object.unknown(true):

对于所有键类型的通用传递,使用object.unknown(true)

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

回答by Niels Keurentjes

The correct answer is actually to use object.unknown(true).

正确答案实际上是使用object.unknown(true).

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