如何通过Golang跳过对空数组的JSON验证

huangapple go评论92阅读模式
英文:

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&#39;s because your Authors validation string is `&quot;omitempty,min=1,dive,min=3&quot;`. The length of an empty slice is 0, which is &lt;1.

If you replace the validation string with `&quot;omitempty,min=0,dive,min=3&quot;` instead, it&#39;ll pass.

</details>



huangapple
  • 本文由 发表于 2022年2月27日 03:51:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/71279829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定