Joi 验证:如何在对象负载中要求至少一个键

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

提问人:kriskanya 提问时间:11/15/2023 更新时间:11/15/2023 访问量:22

问:

Joi 似乎不遵守以下验证中的条件:.or

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')

传入有效负载中应包含一个或多个这些对象键。在本例中,有效载荷如下:

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

响应:

ValidationError: "INVERTED_ROW" is required

根据文档(https://joi.dev/api/?v=17.9.1#objectorpeers-options),我希望这能起作用。有什么想法吗?谢谢!

JavaScript TypeScript 验证 JOI

评论


答:

0赞 ihtisham javed 11/15/2023 #1

正如你提到的“一个或多个”。所以我假设你不在乎哪个密钥存在。

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);