如何在Joi中允许对象包含任意额外键?
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

