简体   繁体   中英

How can I use Joi to validate an object with unknown keys and check that the values are scalar types?

I have an object whose keys I cannot determine ahead of time. How can I enforce specific types (scalar types) for the values using Joi?

Example object with unknown keys:

const obj = {
  x: "foo",
  y: 7,
  z: true,
  p: { m: 1, n: false },
  q: [ "a", "b", "c" ]
}

Since I only want to accept scalar types, it means that keys p and q should cause a validation failure.

How can I achieve this with Joi?

So far I have tried this but it allows non-scalar values like ['a', 'b', 'c'] :

Joi.object().pattern(Joi.string(), Joi.boolean(), Joi.number())

Got it working with this

const validationSchema = Joi.object().pattern(
  Joi.string(),
  Joi.alternatives().try(Joi.number(), Joi.string(), Joi.boolean())
);

See sandbox

https://codesandbox.io/s/jovial-paper-hqiun

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM