最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Joi Validation: Is there a way to allow unknown keys for several schema objects in one go - Stack Overflow

programmeradmin0浏览0评论

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. Is there a way to do it for all in one 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 })

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. Is there a way to do it for all in one 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 })
Share asked Mar 4, 2021 at 9:18 Mohnish MMohnish M 1233 silver badges14 bronze badges 1
  • But I'm not able to make API calls. I get this "\"c\" is not allowed" message without using the above rule. – Mohnish M Commented Mar 4, 2021 at 10:25
Add a ment  | 

1 Answer 1

Reset to default 5

You can use .defaults to create your own custom joi which in this case will have allowUnkown set true as default:

// 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 
}));

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论