简体   繁体   中英

Create a schema which allows any key, but with a defined object value

If I have some data like this:

params: {
  fieldOne: {
    a: 'a1',
    b: 'b1'
  },
  fieldTwo: {
    a: 'a2',
    b: 'b2'
  }
}

I'm trying to write a joi schema that will validate that params is an object with any keys, that have values as objects with a and b .

I'm struggling to figure out how to allow any key in the value of params , yet still validate the value.

const schema = joi.object().keys({
  params: joi.object().required().keys({
    // How to allow any keys here, but require that the value is an object with keys a and b?
  })
});

You can use object.pattern(pattern, schema, [options]) .

Specify validation rules for unknown keys matching a pattern

const schema = joi.object().keys({
    params: joi.object().pattern(
        // this is the 'pattern' of the key name
        // you can also use a regular expression for further refinement
        joi.string(),
        // this is the schema for the key's value
        joi.object().keys({
            a: joi.string().required(),
            b: joi.string().required()
        })
    ).required()
});

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