Skip to content

条件字段#

某些字段可能仅在其他字段存在时才为必需字段。这在 JSON Schema 中被称为 dependentRequired

Struct Tag#

在 Huma 中,支持使用 dependentRequired 标签来为字段应用条件性要求,如以下示例所示:

example.go
type MyInput struct {
    Value      string `json:"value,omitempty" dependentRequired:"dependent1,dependent2"`
    Dependent1 string `json:"dependent1,omitempty"`
    Dependent2 string `json:"dependent2,omitempty"`
}

在上例中,所有字段均为可选,但如果发送了 value,则必须同时发送 dependent1dependent2

Schema#

也可以直接在 schema 中进行更改,而不使用 struct 标签。为此,需要将所需的 schema 中的属性 DependentRequired 设置为 map[string][]string,其中 map 的键是 struct 标签将创建的字段,字符串切片则是依赖字段。