Merrick
Merrick

Reputation: 237

Joi validate array of objects, such that only one object has specific property

I've been reading the Joi API doc for a while & though I suspect what I want to do is possible, I'm not seeing the solution.

Given the following, how can I validate that only one thing has the special property:

let thing = {
  name: Joi.string(),
  special: Joi.boolean(),
}

let manyThings = {
  things: Joi.array().items(thing),
}

Upvotes: 2

Views: 5734

Answers (1)

Cuthbert
Cuthbert

Reputation: 2998

If you're okay with having the first item in the array be the object that has the special property, you can use array.ordered and define a second schema for the subsequent objects.

var joi = require('joi');

var thingSchmea = joi.object().keys({
    name: joi.string().required(),
    special: joi.boolean().required()
});

var thingWithoutSpecialSchema = joi.object().keys({
    name: joi.string().required()
});

var manyThingsSchema = joi.array().ordered(thingSchmea.required()).items(thingWithoutSpecialSchema);


var t = [
    {
        name: 'cuthbert',
        special: true
    },
    {
        name: 'roland',
        special: true
    },
    {
        name: 'jake'
    },
    {
        name: 'susan'
    }
];

var result = joi.validate(t, manyThingsSchema);

console.log(JSON.stringify(result, null, 2));

The variable t will fail validation because the second item in the array has a special property.

Upvotes: 2

Related Questions