joi icon indicating copy to clipboard operation
joi copied to clipboard

Alternatives inside array items with refs to parent fields

Open ghost opened this issue 10 years ago • 7 comments

Context

  • node version: 5.9.1
  • joi version: 8.1.0 and git@master

I'm trying to use when() to set conditions for fields that are defined inside an array item. I haven't had any luck. Am I missing something? I can't think of a reason this shouldn't be supported. Thought this might be related to #892 but even with code post #893 I'm not seeing what I expect.

var Joi = require('joi');

var schema = Joi.object().keys({
  a: Joi.number(),
  b: Joi.array().items({
    c: Joi.when('a', {
      is: 1,
      then: Joi.string().valid(['x'])
    })
  })
});

var data = {
  a: 1,
  b: [{c: 'not-x'}]
};

Joi.validate(data, schema);

//=> { error: null, value: { a: 1, b: [ [Object] ] } }

ghost avatar May 19 '16 22:05 ghost

https://github.com/hapijs/joi/issues/892

hueniverse avatar May 20 '16 01:05 hueniverse

@hueniverse are you saying this should be fixed by #893 then?

ghost avatar May 20 '16 16:05 ghost

When it's published yes.

hueniverse avatar May 20 '16 17:05 hueniverse

Can you verify? I may be crazy but as I mentioned above, I tried running the example above against the current master code from git. I still get no validation error.

ghost avatar May 20 '16 17:05 ghost

Sorry no. You can't do what you want. You are trying to reference a key outside the object you are in. The c property inside the array object has no siblings which the reference is trying to resolve. You are trying to climb out of that object and into the parent of the array which is not supported (and is unlikely to be ever supported because it will create really broken rules).

hueniverse avatar May 21 '16 00:05 hueniverse

@jparkerCAA I got same, I fixed my issue via context. I'm not sure if this one may help you. Maybe there is another way around to access parent ref

var Joi = require('joi');

var schema = Joi.object().keys({
  a: Joi.number(),
  b: Joi.array().items({
    c: Joi.when('$a', {
      is: 1,
      then: Joi.string().valid(['x'])
    })
  })
});

var data = {
  a: 1,
  b: [{c: 'not-x'}]
};

Joi.validate(data, schema, {
  context: {
    a: data.a    
  }
});

kamote avatar Mar 07 '17 03:03 kamote

There is not, parent refs are inaccessible by design. Here they are considered siblings, which is why it works.

Marsup avatar Mar 07 '17 08:03 Marsup