如何通过 Golang 跳过空数组的 json 验证
我想跳过对特定字段的 json 文件中的空数组的验证。下面您可以看到 Book 结构定义,如果 json 文件中没有声明作者,则可以验证该定义。另一方面,如果为作者定义了空数组,则会失败。是否可以使用现有标签实现此行为,或者我是否必须定义自定义验证器?
type Book struct {
Title string `json:"title" validate:"min=2"`
Authors `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": "A Book"
}
失败,显示“Key:'Book.Authors'错误:'Authors'的字段验证在'min'标签上失败”
{
"title": "A Book",
"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": []
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是因为您的作者验证字符串为
"omitempty,min=1,dive,min=3"
。空切片的长度为0,即<1。如果您将验证字符串替换为
"omitempty,min=0,dive,min=3"
,它将通过。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.