英文:
How to compose snake case binding tag with go-playground/validator?
问题
作为标题,由于我是一个对golang新手,对于一些自定义格式的绑定标签有些困惑。
例如,
有一个结构体有几个字段,如下所示:
type user struct {
name `json:"name" binding:"required"`
hobby `json:"name" binding:"required"`
}
name字段应该只支持小写字母和下划线(例如john_cage,david),但是在阅读验证器的文档后,我仍然不知道如何实现。
验证器的github
对于我的情况,是否有任何好的建议或解决方案?提前谢谢。
阅读文档,搜索类似的问题,尝试编写自定义的绑定标签等。
英文:
As title, since I'm a newbie to golang, I'm a little bit confused of the binding tag for some custom format.
For example,
there's a struct with a few of fields like this
type user struct {
name `json:"name" binding:"required"`
hobby `json:"name" binding:"required"`
}
and the name field is supposed to support lowercase and underscore only (e.g. john_cage, david)
but after I read the document of validator, still have no idea about that.
validator github
Is there's any good suggestion or solution for my case? Thanks in advance.
Read the document, google similar questions, try to compose the customer binding tag, etc.
答案1
得分: 2
binding
标签来自gin
,validator
的正确结构标签是validate
。由于snake_case
没有内置的验证规则,你需要自己创建。并且不要忘记导出字段(Hobby
,Name
)。如果不导出(例如:hobby
,name
),验证器将忽略这些字段。
package main
import (
"fmt"
"strings"
"github.com/go-playground/validator/v10"
)
type user struct {
Hobby string `json:"name" validate:"required,snakecase"`
}
func main() {
v := validator.New()
_ = v.RegisterValidation("snakecase", validateSnakeCase)
correct := user{"playing_game"}
Incorrect := user{"playingGame"}
err := v.Struct(correct)
fmt.Println(err) // nil
err = v.Struct(Incorrect)
fmt.Println(err) // error
}
const allows = "abcdefghijklmnopqrstuvwxyz_"
func validateSnakeCase(fl validator.FieldLevel) bool {
str := fl.Field().String()
for i := range str {
if !strings.Contains(allows, str[i:i+1]) {
return false
}
}
return true
}
如果你想通过gin
注册这个函数,请查看这个链接。
英文:
binding
tag is from gin
, correct struct tag for validator
is validate
. Since there is no vaildation for snake_case, you should make your own. And don't forget to export the fields(Hobby
, Name
). If you not, (ex: hobby
, name
) validator will ignore the fields.
package main
import (
"fmt"
"strings"
"github.com/go-playground/validator/v10"
)
type user struct {
Hobby string `json:"name" validate:"required,snakecase"`
}
func main() {
v := validator.New()
_ = v.RegisterValidation("snakecase", validateSnakeCase)
correct := user{"playing_game"}
Incorrect := user{"playingGame"}
err := v.Struct(correct)
fmt.Println(err) // nil
err = v.Struct(Incorrect)
fmt.Println(err) // error
}
const allows = "abcdefghijklmnopqrstuvwxyz_"
func validateSnakeCase(fl validator.FieldLevel) bool {
str := fl.Field().String()
for i := range str {
if !strings.Contains(allows, str[i:i+1]) {
return false
}
}
return true
}
If you want to register the function via gin
, check this out
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论