Search code examples
javascriptjoi

How to use Joi to validate map object (map keys and map values)


For example, there is the following map:

keys = type string, 5 characters long
values = type number

Example:

test = {
   "abcde": 1
   "12345": 2
   "ddddd": 3
}

How to write Joi Scheme that validates key are of type string with 5 characters and values are of type number


Solution

  • It looks like you're trying to validate an object with unknown keys, but you know what general pattern the object must match. You can achieve this by using Joi's .pattern() method:

    object.pattern(pattern, schema)

    Specify validation rules for unknown keys matching a pattern where:

    pattern - a pattern that can be either a regular expression or a joi schema that will be tested against the unknown key names.

    schema - the schema object matching keys must validate against.

    So for your instance:

    Joi.object().pattern(Joi.string().length(5), Joi.number());