简体   繁体   中英

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 ?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM