You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Joi中允许对象包含任意额外键?

How to Allow Extra/Unknown Keys in a Joi Schema

Got it, I’ve run into this exact issue before! By default, Joi’s object schemas are strict—they’ll throw an error if you pass any keys that aren’t explicitly defined in your schema. To fix this and allow arbitrary extra keys (like your c example), you just need to use the .unknown() method.

Here’s how to modify your existing schema:

Solution 1: Allow All Unknown Keys

Add .unknown(true) (or just .unknown(), since true is the default parameter) to your schema definition:

const schema = Joi.object().keys({
  a: Joi.string().required(),
  b: Joi.string().required()
}).unknown(true); // This line enables arbitrary extra keys

Or using the more modern Joi syntax (without .keys()):

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

Once you add this, passing an object with extra keys like { a: "foo", b: "bar", c: "baz" } will validate successfully instead of throwing an error.

Bonus: Allow Specific Unknown Keys (Optional)

If you ever need to restrict extra keys to a pattern instead of allowing everything, you can use .pattern() instead. For example, to allow any keys starting with c:

const schema = Joi.object({
  a: Joi.string().required(),
  b: Joi.string().required()
}).pattern(/^c/, Joi.string()); // Only allows extra keys starting with "c"

But since your request is to allow any extra keys, the .unknown(true) approach is exactly what you need.

内容的提问来源于stack exchange,提问作者Anand Undavia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:36:37