sk-matrix-project/backend/golang/matrix-middle-service/pkg/utils/validator/validator.go

45 lines
1.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package validator
import (
"errors"
"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"
"reflect"
)
var zhLocales = zh.New()
var validate = validator.New()
var uni = ut.New(zhLocales)
var trans, _ = uni.GetTranslator("zh")
// 验证器注册翻译器
var _ = zhTranslations.RegisterDefaultTranslations(validate, trans)
func init() {
//注册一个函数获取struct tag里自定义的label作为字段名
validate.RegisterTagNameFunc(func(fld reflect.StructField) string {
if label := fld.Tag.Get("label"); len(label) > 0 {
return label
}
if jsonField := fld.Tag.Get("json"); len(jsonField) > 0 {
return jsonField
}
return fld.Name
})
}
func ValidateStruct(data interface{}) (err error) {
err = validate.Struct(data)
if err != nil {
for _, e := range err.(validator.ValidationErrors) {
err = errors.New(e.Translate(trans))
break
}
}
return
}