joi icon indicating copy to clipboard operation
joi copied to clipboard

Problems with assertions and references.

Open a00andos opened this issue 12 years ago • 2 comments

Consider this schema:

Joi.object().keys({
  name: Joi.string(),
  bindings: Joi.array().includes(Joi.object().keys({
    name: Joi.string(),
    service: Joi.string()
  }).and('name', 'service'))
});

I have a two properties named name. The first at the top, and another inside an array with embedded objects. Lets say i want name in all these embedded object to be equal to name in the outer object. Can I achieve this somehow with references or assertions? I have tried, but not succeeded.

a00andos avatar Oct 29 '14 12:10 a00andos

@a00andos

You can't ref() up the object tree, but you can work around it by using a context object in the call to validate():

var schema = Joi.object().keys({
  name: Joi.string(),
  bindings: Joi.array().includes(Joi.object().keys({
    name: Joi.ref('$name'),
    service: Joi.string()
  }).and('name', 'service'))
});

var o = {
    name: 'joi user',
    bindings: [{ name: 'joi user', service: 'some service' }]
};

Joi.validate(o, schema, { context: { name: o.name } }, function (err, value) {
    if (err) {
        return console.log(err);
    }

    console.log('success');
});

jaswilli avatar Oct 29 '14 18:10 jaswilli

This issue seems dead, re-open if still needed.

Marsup avatar Apr 02 '15 15:04 Marsup