Alok
Alok

Reputation: 10544

How to validate nested object whose keys should match with outer objects another key whose value is array using Joi?

I have object which I want to validate.

// valid object because all values of keys are present in details object
var object = {
    details: {
        key1: 'stringValue1',
        key2: 'stringValue2',
        key3: 'stringValue3'
    },
    keys: ['key1', 'key2', 'key3']
}

// invalid object as key5 is not present in details
var object = {
    details: {
        key4: 'stringValue4'
    },
    keys: ['key4', 'key5']
}

// invalid object as key5 is not present and key8 should not exist in details
var object = {
    details: {
        key4: 'stringValue4',
        key8: 'stringValue8',            
    },
    keys: ['key4', 'key5']
}

All the keys present in keys should be present in details also.

I tried this using Joi.ref()

var schema = Joi.object({
    details: Joi.object().keys(Object.assign({}, ...Object.entries({...Joi.ref('keys')}).map(([a,b]) => ({ [b]: Joi.string() })))),
    keys: Joi.array()
})

But this is not working because Joi.ref('keys') will get resolved at validation time.

How can I validate this object using Joi?

Upvotes: 0

Views: 1039

Answers (2)

User863
User863

Reputation: 20039

Using object.pattern and array.length

var schema = Joi.object({
  details: Joi.object().pattern(Joi.in('keys'), Joi.string()),
  keys: Joi.array().length(Joi.ref('details', {
      adjust: (value) => Object.keys(value).length
    }))
});

stackblitz

Upvotes: 2

Aritra Chakraborty
Aritra Chakraborty

Reputation: 12542

You can validate the array(if you want) then make a dynamic schema and validate that.

const arrSchema = Joi.object({
    keys: Joi.array()
});

then,

const newSchema = Joi.object({
    details: Joi.object().keys(data.keys.reduce((p, k) => {
        p[k] = Joi.string().required();
        return p;
    },{})),
    keys: Joi.array()
})

This should probably do it.

You have to set allowUnknown: true in validate() option.

Upvotes: 1

Related Questions