Require an Object to Contain at Least One Key in a Joi Schema

When validating JSON objects with Joi in JavaScript we sometimes need an object to have any one of a set of possible keys, i.e. one or more of the specific keys given.

The schema below achieves this with the or() function.

const customerSchema = Joi.object().keys({
  id: Joi.string().optional(),
  accountNumber: Joi.number().optional(),
  emailAddress: Joi.string().optional()
})
.or('id', 'accountNumber', 'emailAddress') // At least one of these keys must be in the object to be valid.
.required()

If we supply a JSON object like below to the Joi schema validate function, we will see a Joi schema validation error similar to the example.

{
  "name": "test"
}

Joi validation error:

"message": "object must contain at least one of [id, accountNumber, emailAddress]"

However, any of the following are valid examples:

{
  "id": "1234"
}
{
  "id": "1234",
  "emailAddress": "test@test.com"
}

Note that we can also use the related functions and(), xor(), nand(), and others to achieve other logical requirements on object keys.

 

Leave a Reply

Your email address will not be published. Required fields are marked *