object.pattern() is not working correctly inside array.items() in Joi

此生再无相见时 提交于 2019-12-24 22:25:07

问题


I am trying to validate nested object whose keys should match with outer objects another key whose value is array using Joi
I tried to use object.pattern and array.length which is demonstrated at How to validate nested object whose keys should match with outer objects another key whose value is array using Joi?

But that is not working with array.items()

var object = {
    details:[{
        key1: 'someValue',
        key2: 'someValue',
        key3: 'someValue'
    },{
        key1: 'someValue',
        key2: 'someValue',
        key3: 'someValue'
    }],
    keys: ['key1', 'key2', 'key3']
}

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

console.log(schema.validate(object)) // this should not give error but I am getting error

I am getting error

{ value:
   { details: [ [Object], [Object] ],
     keys: [ 'key1', 'key2', 'key3' ] },
  error:
   { ValidationError: "details[0].key1" is not allowed
     _original: { details: [Array], keys: [Array] },
     details: [ [Object] ] } }

How to make this validation working without hardcoding keys?


回答1:


Joi.ref('details', {adjust: (value) => Object.keys(value).length}),

Problem - Here value refers the details which is an array. So Object.keys(<details-array>).length won't work as expected

solution - map value array with Object.keys().length and use the maximum as given below


Joi.object().pattern(Joi.in('keys'), Joi.string()),

Problem - keys refers the sibling of details

solution - add / as prefix which is root of object


var schema = Joi.object({
  details: Joi.array().items(Joi.object().pattern(Joi.in('/keys'), Joi.string())),
  keys: Joi.array().length(
    Joi.ref('details', {
      adjust: value => {
        return Math.max(...value.map(o => Object.keys(o).length));
      }
    })
  )
});

stackblitz

Reference

https://github.com/hapijs/joi/blob/master/API.md#Relative-references



来源:https://stackoverflow.com/questions/58876986/object-pattern-is-not-working-correctly-inside-array-items-in-joi

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