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

javascript - Is there a way to validate dynamic key names in a Joi schema? - Stack Overflow

programmeradmin0浏览0评论

Is there a way I can validate a value like this with Joi so that I can verify it is an object with zero or more keys (of any name) and that each have values of either a string, number or boolean?

{
  dynamicallyNamedKey1: 'some value',
  dynamicallyNamedKey2: 4
}

Is there a way I can validate a value like this with Joi so that I can verify it is an object with zero or more keys (of any name) and that each have values of either a string, number or boolean?

{
  dynamicallyNamedKey1: 'some value',
  dynamicallyNamedKey2: 4
}
Share Improve this question edited Oct 23, 2017 at 18:31 Iain J. Reid 9881 gold badge11 silver badges24 bronze badges asked Mar 27, 2017 at 15:46 19771977 2,9107 gold badges30 silver badges43 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

You're going to want to use Joi's object().pattern() method. It's specifically for validating objects with unknown keys.

To match against one or more datatypes on a single key you'll need alternatives().try() (or simply pass an array of Joi types).

So the rule to match your needs would be:

Joi.object().pattern(/^/, Joi.alternatives().try(Joi.string(), Joi.number(), Joi.boolean()))
发布评论

评论列表(0)

  1. 暂无评论