trans.go 1014 Bytes
Newer Older
kzkzzzz's avatar
kzkzzzz committed
1 2 3 4 5 6 7 8 9 10 11
package validate

import (
	"github.com/go-playground/locales/en"
	"github.com/go-playground/locales/zh"
	ut "github.com/go-playground/universal-translator"
	"github.com/go-playground/validator/v10"
	zhTranslations "github.com/go-playground/validator/v10/translations/zh"
)

var (
kzkzzzz's avatar
kzkzzzz committed
12 13
	vt    *validator.Validate
	trans ut.Translator
kzkzzzz's avatar
kzkzzzz committed
14 15 16 17 18 19 20
)

func newTranslate(v *validator.Validate) ut.Translator {
	zhT := zh.New()
	enT := en.New()

	uni := ut.New(enT, zhT)
kzkzzzz's avatar
kzkzzzz committed
21 22 23
	tr, _ := uni.GetTranslator("zh")
	_ = zhTranslations.RegisterDefaultTranslations(v, tr)
	return tr
kzkzzzz's avatar
kzkzzzz committed
24 25 26 27
}

func init() {
	vt = validator.New()
kzkzzzz's avatar
kzkzzzz committed
28
	trans = newTranslate(vt)
kzkzzzz's avatar
kzkzzzz committed
29 30 31
}

func GrtTrans() ut.Translator {
kzkzzzz's avatar
kzkzzzz committed
32
	return trans
kzkzzzz's avatar
kzkzzzz committed
33 34 35 36 37
}

func Struct(data interface{}) error {
	return vt.Struct(data)
}
kzkzzzz's avatar
kzkzzzz committed
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53

func TransError(err error) (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
}