...
1 package main
2
3 import (
4 "fmt"
5
6 "github.com/go-playground/locales/en"
7 ut "github.com/go-playground/universal-translator"
8 "github.com/go-playground/validator/v10"
9 en_translations "github.com/go-playground/validator/v10/translations/en"
10 )
11
12
13 type User struct {
14 FirstName string `validate:"required"`
15 LastName string `validate:"required"`
16 Age uint8 `validate:"gte=0,lte=130"`
17 Email string `validate:"required,email"`
18 FavouriteColor string `validate:"iscolor"`
19 Addresses []*Address `validate:"required,dive,required"`
20 }
21
22
23 type Address struct {
24 Street string `validate:"required"`
25 City string `validate:"required"`
26 Planet string `validate:"required"`
27 Phone string `validate:"required"`
28 }
29
30
31 var (
32 uni *ut.UniversalTranslator
33 validate *validator.Validate
34 )
35
36 func main() {
37
38
39
40 en := en.New()
41 uni = ut.New(en, en)
42
43
44
45 trans, _ := uni.GetTranslator("en")
46
47 validate = validator.New()
48 en_translations.RegisterDefaultTranslations(validate, trans)
49
50 translateAll(trans)
51 translateIndividual(trans)
52 translateOverride(trans)
53 }
54
55 func translateAll(trans ut.Translator) {
56
57 type User struct {
58 Username string `validate:"required"`
59 Tagline string `validate:"required,lt=10"`
60 Tagline2 string `validate:"required,gt=1"`
61 }
62
63 user := User{
64 Username: "Joeybloggs",
65 Tagline: "This tagline is way too long.",
66 Tagline2: "1",
67 }
68
69 err := validate.Struct(user)
70 if err != nil {
71
72
73 errs := err.(validator.ValidationErrors)
74
75
76
77
78
79 fmt.Println(errs.Translate(trans))
80 }
81 }
82
83 func translateIndividual(trans ut.Translator) {
84
85 type User struct {
86 Username string `validate:"required"`
87 }
88
89 var user User
90
91 err := validate.Struct(user)
92 if err != nil {
93
94 errs := err.(validator.ValidationErrors)
95
96 for _, e := range errs {
97
98 fmt.Println(e.Translate(trans))
99 }
100 }
101 }
102
103 func translateOverride(trans ut.Translator) {
104
105 validate.RegisterTranslation("required", trans, func(ut ut.Translator) error {
106 return ut.Add("required", "{0} must have a value!", true)
107 }, func(ut ut.Translator, fe validator.FieldError) string {
108 t, _ := ut.T("required", fe.Field())
109
110 return t
111 })
112
113 type User struct {
114 Username string `validate:"required"`
115 }
116
117 var user User
118
119 err := validate.Struct(user)
120 if err != nil {
121
122 errs := err.(validator.ValidationErrors)
123
124 for _, e := range errs {
125
126 fmt.Println(e.Translate(trans))
127 }
128 }
129 }
130
View as plain text