Joi: Support for validating values of key-value pairs in objects

Created on 4 Jul 2015  路  4Comments  路  Source: sideway/joi

I have a situation where I am trying to maintain a mapping of string keys to numeric values. I can't know what the string keys are ahead of time, but I want to assert that all the values are positive numbers.

I didn't see a way to do this in the docs. Did I miss something or should this be a feature request?

Example object:

{
   "CADUSD": 0.80,
   "USDCAD": 1.30,
   "EURUSD": 1.15,
   "USDEUR": 0.9
}
support

Most helpful comment

var schema = Joi.object().pattern(/\w+/, Joi.number().positive());

That will check any key that matches w+ and make sure the value is a positive number. Pattern doesn't validate the keys as there would be little point to doing that, it's just to give you a matcher to access the values.

All 4 comments

Check out https://github.com/hapijs/joi#objectpatternregex-schema. It lets you set up a schema against keys based on a regular expression.

Sorry, my original post may not have been clear. I see how to validate the keys of the key-value pairs. I'm looking to validate the values (the numbers in the example).

var schema = Joi.object().pattern(/\w+/, Joi.number().positive());

That will check any key that matches w+ and make sure the value is a positive number. Pattern doesn't validate the keys as there would be little point to doing that, it's just to give you a matcher to access the values.

Ah, I see it now. Sorry about that 鈥撀爐hanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JbIPS picture JbIPS  路  4Comments

a-c-m picture a-c-m  路  3Comments

kevbook picture kevbook  路  4Comments

builtbybrayne picture builtbybrayne  路  4Comments

sergibondarenko picture sergibondarenko  路  3Comments