mycommon/myvalidator/validator.go

70 lines
1.3 KiB
Go

package myvalidator
import (
"fmt"
"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"
"github.com/go-playground/validator/v10"
//zhTranslations "github.com/go-playground/validator/v10/translations/zh"
enTranslations "github.com/go-playground/validator/v10/translations/en"
)
var (
vt *validator.Validate
trans ut.Translator
)
func Init() {
vt = validator.New()
trans = RegisterTranslate(vt)
}
func RegisterTranslate(v *validator.Validate) ut.Translator {
//zhT := zh.New()
enT := en.New()
uni := ut.New(enT, enT)
tr, _ := uni.GetTranslator("en")
_ = enTranslations.RegisterDefaultTranslations(v, tr)
return tr
}
// Verify 验证结构体
func Verify(data interface{}) error {
return vt.Struct(data)
}
// VerifyTrans 验证结构体并翻译
func VerifyTrans(data interface{}) error {
return Trans(vt.Struct(data))
}
func Trans(err error) error {
return GetTransError(trans, err)
}
// GetTransError 翻译错误信息
func GetTransError(trans ut.Translator, err error) error {
if err == nil {
return nil
}
var msg string
switch v := err.(type) {
case validator.ValidationErrors:
if len(v) > 0 {
msg = v[0].Translate(trans)
} else {
msg = v.Error()
}
case validator.FieldError:
msg = v.Translate(trans)
default:
msg = err.Error()
}
return fmt.Errorf(msg)
}