Joi: Validating an array of objects with each object having its own set of rules

Created on 29 Aug 2018  路  6Comments  路  Source: sideway/joi

I am trying to validate an array that has strict rules for the items inside the array. For example:

Array Requirements:
The array must contain an object that has property "foo" with value "bar".
The array can only contain one element where "foo" equals "bar".
If the array contains an object that has property "foo" with value "baz" the array can only contain one element where "foo" equals "baz".
The array can contain any number of objects with property "foo" set to any value.

Valid Arrays:

[{ "foo": "bar" }, {"foo": "baz"}, {"foo": "bop"}]
[{"foo": "bar"}, {"foo": "bop"}, {"foo": "it"} ]
[{"foo": "bar"}]

Invalid Arrays:

[]
[{"foo": "bar"}, {"foo": "bar"}]
[{"foo": "bar"}, {"foo": "baz"}, {"foo": "baz"}]
[{"foo": "baz"}]
[{"foo": "bop"}, {"foo": "it"}]

Is this possible using Joi?

support

All 6 comments

Have you looked at unique() ?

Oops, I messed up my initial criteria.

The array can contain any number of objects with property "foo" set to any value.

Should be:
The array can contain any number of objects with the same value for the key "foo".

Valid:
[{"foo": "bar"}, {"foo": "bop"}, {"foo": "bop"}]

Thanks, I got it to work using unique.

Joi.object({
  list: Joi.array().unique((a, b) => {
    if(a.foo.match(/'bar'|'baz'/)) {
      return a.foo === b.foo;
    }
  })
});

The only thing I am still having trouble with is ensuring that the array has at least one object with the key of "foo" set to "bar". Do you know of anyway to enforce that?

Alright I figured it out. I just had to set the array items description to include the two possible types of objects and require the one that needs to be present at least once.

Joi.object({
  list: Joi.array()
    .items([Joi.object({ "foo": "bar" }).required(), Joi.object({ "foo": Joi.string().required() })])
    .unique((a, b) => {
      if(a.foo.match(/'bar'|'baz'/)) {
        return a.foo === b.foo;
      }
    })
});

This thread has been automatically locked due to inactivity. Please open a new issue for related bugs or questions following the new issue template instructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mohamadresaaa picture mohamadresaaa  路  3Comments

longweiquan picture longweiquan  路  3Comments

kevbook picture kevbook  路  4Comments

normancarcamo picture normancarcamo  路  3Comments

alekbarszczewski picture alekbarszczewski  路  3Comments