Joi validation: How to require at least one key in an object payload

32 Views Asked by At

Joi doesn't seem to be respecting the .or condition in the following validation:

export const PAYLOAD = Joi.object().keys({
  PUSH_UP:        Joi.any(),
  INVERTED_ROW:   Joi.any(),
  DIP:            Joi.any(),
  CHIN_UP:        Joi.any(),
  PULL_UP:        Joi.any(),
  GOBLET_SQUAT:   Joi.any(),
  BACK_EXTENSION: Joi.any()
}).or('PUSH_UP', 'INVERTED_ROW', 'DIP', 'CHIN_UP', 'PULL_UP', 'GOBLET_SQUAT', 'BACK_EXTENSION')

The incoming payload should have one or more of those object keys in it. In this case, the payload is as follow:

{
  "BACK_EXTENSION": {
    "reps": 30,
    "exerciseId": 7
  },
  "PUSH_UP": {
    "reps": 1,
    "exerciseId": 1
  }
}

response:

ValidationError: "INVERTED_ROW" is required

Based upon the docs (https://joi.dev/api/?v=17.9.1#objectorpeers-options), I would expect this to work. Any ideas? Thanks!

1

There are 1 best solutions below

0
ihtisham javed On

As you mentioned "One or more". So I am assuming you don't care which one of the key is present.

export const PAYLOAD = Joi.object().keys({
  PUSH_UP:        Joi.any(),
  INVERTED_ROW:   Joi.any(),
  DIP:            Joi.any(),
  CHIN_UP:        Joi.any(),
  PULL_UP:        Joi.any(),
  GOBLET_SQUAT:   Joi.any(),
  BACK_EXTENSION: Joi.any()
}).min(1);