如何使用go-playground/validator组件来组合蛇形命名绑定标签?

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

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标签来自ginvalidator的正确结构标签是validate。由于snake_case没有内置的验证规则,你需要自己创建。并且不要忘记导出字段(HobbyName)。如果不导出(例如:hobbyname),验证器将忽略这些字段。

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
}

Playground

如果你想通过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
}

Playground

If you want to register the function via gin, check this out

huangapple
  • 本文由 发表于 2022年11月23日 15:24:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/74543080.html
匿名

发表评论

匿名网友

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

确定