| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- package validator
- import (
- "github.com/gin-gonic/gin"
- "github.com/gin-gonic/gin/binding"
- "github.com/go-playground/locales/zh"
- ut "github.com/go-playground/universal-translator"
- "github.com/go-playground/validator/v10"
- zh_translations "github.com/go-playground/validator/v10/translations/zh"
- "reflect"
- )
- var trans ut.Translator
- func init() {
- uni := ut.New(zh.New())
- trans, _ = uni.GetTranslator("zh")
- if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
- //注册翻译器
- _ = zh_translations.RegisterDefaultTranslations(v, trans)
- //注册一个函数,获取struct tag里自定义的label作为字段名
- v.RegisterTagNameFunc(func(fld reflect.StructField) string {
- name := fld.Tag.Get("label")
- return name
- })
- }
- }
- // ValidatorData 验证数据
- func ValidatorData(c *gin.Context, data interface{}) (string, bool) {
- if err := c.ShouldBind(data); err != nil {
- for _, v := range err.(validator.ValidationErrors) {
- return v.Translate(trans), false
- }
- }
- return "", true
- }
|