Is there a way to validate dynamic key names in a Joi schema?

陌路散爱 提交于 2019-11-26 21:53:35

问题


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
}

回答1:


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()))


来源:https://stackoverflow.com/questions/43050870/is-there-a-way-to-validate-dynamic-key-names-in-a-joi-schema

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