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

余生长醉 提交于 2019-12-04 06:21:27

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/58713032/how-to-validate-nested-object-whose-keys-should-match-with-outer-objects-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!