How to allow any other key in Joi [duplicate]

折月煮酒 提交于 2020-02-23 08:42:08

问题


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 a and b. If I pass any other key, say, c, it throws an error saying that c is not allowed.


回答1:


You can add unknown keys using object.pattern(regex, schema) like this:

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



回答2:


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

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


来源:https://stackoverflow.com/questions/49897639/how-to-allow-any-other-key-in-joi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!