Search code examples
jsonnode.jsvalidationhapi.jsjoi

Node.js/Hapijs - Validate all keys and values in JSON object payload without naming keys


Some of the functionality in my API involves taking POST-sent payload input and handing it off to another application for processing. The payload input is always sent as a JSON object, and the values must always be numeric. However, because there are hundreds of different variations of the JSON objects (because there are a growing variety of models they are matched to in the other application), it is not feasible for me to name each of the keys and values for the validation config option in the POST route I've defined in Hapijs.

I'm wishing I could do something like this, but imagine there will have to be more hack-ish work-around:

config: {
    validate: {
        payload: Joi.object().keys(Joi.number())    
    }
}

Perhaps there is some way to loop through the object and ensure that the values are all numeric-- within the validate option-- but that feels like it could be quite inefficient.


Solution

  • You can use Joi.object().pattern(regex, schema); to validate unknown keys.

    If you just want to check the properties are all numbers you can simply do:

    config: {
        payload: { 
            output: data 
        },
        validate: {
            payload: Joi.object().pattern(/.*/, Joi.number()) // Any key   
        }
    }
    

    If you also wanted to validate the keys, you can add a more specific regex.

    Joi example that only allows keys named a-z:

    var Joi = require('joi');
    
    var object = {
        a: 1,
        b: 2,
        c1: 3  // <--- Bad key
    };
    
    var schema = Joi.object().pattern(/^[a-z]$/, Joi.number());
    
    Joi.assert(object, schema);
    

    Output:

    Error: {
      "a": 1,
      "b": 2,
      "c1" [1]: 3
    }
    
    [1] "c1" is not allowed