gpt4 book ai didi

Json 模式根据另一个字段验证一个字段的长度

转载 作者:行者123 更新时间:2023-12-02 20:15:00 25 4
gpt4 key购买 nike

我有一个包含两个字段的 JSON 架构。 fieldA 和 fieldB,fieldA 是一个枚举,fieldB 是一个字符串。我想根据 fieldA 的值对 fieldB 的长度添加一些验证。

properties:
fieldA:
enum:
- VAL1
- VAL2
- VAL3
fieldB:
type: string
pattern: '^[<a-z>{10}|<a-z>{5}]$'

我想验证如果 fieldA 等于 VAL1,则 fieldB 的长度应为 5,否则 fieldB 的长度应为 10。如何添加此类验证检查?

最佳答案

答案取决于您使用的是 OpenAPI 2.0 ( swagger: '2.0' ) 还是 OpenAPI 3.0 ( openapi: 3.0.0 )。

OpenAPI 2.0

OpenAPI 2.0 不支持条件依赖。您只能在 description 中口头记录此类依赖关系.

OpenAPI 3.0

您可以使用 oneOf描述 OpenAPI 3.0 中的条件依赖关系,类似于您在 JSON Schema 中的做法。以下示例基于对 JSON schema conditional dependency on value 的回答.

注意 oneOf是 OpenAPI 规范的一部分(例如,您可以编写包含 oneOf 的 API 定义),实际工具支持 oneOf可能会有所不同。

type: object
required:
- fieldA
properties:
fieldA:
type: string
enum:
- VAL1
- VAL2
- VAL3
fieldB:
type: string
pattern: '^[a-z]+$'
oneOf:
# If fieldA = VAL1, then fieldB must be 5 chars long
- properties:
fieldA:
enum: [VAL1]
fieldB:
minLength: 5
maxLength: 5
# Otherwise (if fieldA = VAL2 or VAL3) fieldB must be 10 chars long
- properties:
fieldA:
enum: [VAL2, VAL3]
fieldB:
minLength: 10
maxLength: 10

关于Json 模式根据另一个字段验证一个字段的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com