-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.go
72 lines (63 loc) · 1.71 KB
/
validator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package validator
import (
"reflect"
"regexp"
"strings"
"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"
"github.com/hopeio/cherry/utils/log"
)
var (
Validator *validator.Validate
trans ut.Translator
)
func init() {
zhcn := zh.New()
uni := ut.New(zhcn, zhcn)
// this is usually know or extracted from http 'Accept-Language' header
// also see uni.FindTranslator(...)
trans, _ = uni.GetTranslator("zh")
Validator = validator.New()
zh_translations.RegisterDefaultTranslations(Validator, trans)
Validator.RegisterTagNameFunc(func(sf reflect.StructField) string {
if comment := sf.Tag.Get("comment"); comment != "" {
return comment
}
if json := sf.Tag.Get("json"); json != "" {
return json
}
return sf.Name
})
Validator.RegisterValidation("phone", func(fl validator.FieldLevel) bool {
match, _ := regexp.MatchString(`^1[0-9]{10}$`, fl.Field().String())
return match
})
Validator.RegisterTranslation("phone", trans, func(ut ut.Translator) error {
return ut.Add("phone", "{0}必须是一个有效的手机号!", true)
}, translateFunc)
}
func Trans(err error) string {
if err == nil {
return ""
}
var msg []string
ve, ok := err.(validator.ValidationErrors)
if !ok {
log.Error("无效的参数")
return ""
}
for _, v := range ve.Translate(trans) {
msg = append(msg, v)
}
return strings.Join(msg, ",")
}
func translateFunc(ut ut.Translator, fe validator.FieldError) string {
t, err := ut.T(fe.Tag(), fe.Field())
if err != nil {
log.Errorf("警告: 翻译字段错误: %#v", fe)
return fe.(error).Error()
}
return t
}