英文:
how to skip json validation for an empty array via Golang
问题
我想要跳过对 JSON 文件中特定字段的空数组进行验证。下面是 Book 结构体的定义,如果在 JSON 文件中未声明作者,则可以进行验证。然而,如果为作者定义了一个空数组,则验证失败。是否可以通过现有的标签实现这种行为,还是必须定义自定义验证器?
type Book struct {
Title string `json:"title" validate:"min=2"`
Authors []string `json:"authors" validate:"omitempty,min=1,dive,min=3"`
// ...
}
我正在使用 "github.com/go-playground/validator/v10" 包的验证器来验证 Book 结构体:
book := &Book{}
if err := json.Unmarshal(data, book); err != nil {
return nil, err
}
v := validator.New()
if err := v.Struct(book); err != nil {
return nil, err
}
验证成功:
{
"title": "一本书"
}
验证失败,错误信息为 "Key: 'Book.Authors' Error:Field validation for 'Authors' failed on the 'min' tag":
{
"title": "一本书",
"authors": []
}
英文:
I'd like to skip validation for empty arrays in a json file for a specific field. Below you can see Book structs definition, which could be validated if no authors are declared in json file. On the other hand it fails if an empty array is defined for authors. Is it possible to achieve this behavior with existing tags, or do I have to define custom validator?
type Book struct {
Title string `json:"title" validate:"min=2"`
Authors `json:"authors" validate:"omitempty,min=1,dive,min=3"`
// ...
}
I'm validating Book struct via "github.com/go-playground/validator/v10" package's validator:
book := &Book{}
if err := json.Unmarshal(data, book); err != nil {
return nil, err
}
v := validator.New()
if err := v.Struct(book); err != nil {
return nil, err
}
Works:
{
"title": "A Book"
}
Fails with "Key: 'Book.Authors' Error:Field validation for 'Authors' failed on the 'min' tag"
{
"title": "A Book",
"authors": []
}
</details>
# 答案1
**得分**: 5
这是因为你的作者验证字符串是`"omitempty,min=1,dive,min=3"`。空切片的长度为0,小于1。
如果你将验证字符串替换为`"omitempty,min=0,dive,min=3"`,它将通过验证。
<details>
<summary>英文:</summary>
It's because your Authors validation string is `"omitempty,min=1,dive,min=3"`. The length of an empty slice is 0, which is <1.
If you replace the validation string with `"omitempty,min=0,dive,min=3"` instead, it'll pass.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论