Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

joi

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

like image 846
alexpov Avatar asked Oct 31 '25 11:10

alexpov


1 Answers

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());
like image 159
Ankh Avatar answered Nov 03 '25 03:11

Ankh