...
1 package main
2
3 import (
4 "fmt"
5
6 "github.com/go-playground/validator/v10"
7 )
8
9
10 type User struct {
11 FirstName string `validate:"required"`
12 LastName string `validate:"required"`
13 Age uint8 `validate:"gte=0,lte=130"`
14 Email string `validate:"required,email"`
15 Gender string `validate:"oneof=male female prefer_not_to"`
16 FavouriteColor string `validate:"iscolor"`
17 Addresses []*Address `validate:"required,dive,required"`
18 }
19
20
21 type Address struct {
22 Street string `validate:"required"`
23 City string `validate:"required"`
24 Planet string `validate:"required"`
25 Phone string `validate:"required"`
26 }
27
28
29 var validate *validator.Validate
30
31 func main() {
32
33 validate = validator.New(validator.WithRequiredStructEnabled())
34
35 validateStruct()
36 validateVariable()
37 }
38
39 func validateStruct() {
40
41 address := &Address{
42 Street: "Eavesdown Docks",
43 Planet: "Persphone",
44 Phone: "none",
45 }
46
47 user := &User{
48 FirstName: "Badger",
49 LastName: "Smith",
50 Age: 135,
51 Gender: "male",
52 Email: "Badger.Smith@gmail.com",
53 FavouriteColor: "#000-",
54 Addresses: []*Address{address},
55 }
56
57
58 err := validate.Struct(user)
59 if err != nil {
60
61
62
63
64 if _, ok := err.(*validator.InvalidValidationError); ok {
65 fmt.Println(err)
66 return
67 }
68
69 for _, err := range err.(validator.ValidationErrors) {
70
71 fmt.Println(err.Namespace())
72 fmt.Println(err.Field())
73 fmt.Println(err.StructNamespace())
74 fmt.Println(err.StructField())
75 fmt.Println(err.Tag())
76 fmt.Println(err.ActualTag())
77 fmt.Println(err.Kind())
78 fmt.Println(err.Type())
79 fmt.Println(err.Value())
80 fmt.Println(err.Param())
81 fmt.Println()
82 }
83
84
85 return
86 }
87
88
89 }
90
91 func validateVariable() {
92
93 myEmail := "joeybloggs.gmail.com"
94
95 errs := validate.Var(myEmail, "required,email")
96
97 if errs != nil {
98 fmt.Println(errs)
99 return
100 }
101
102
103 }
104
View as plain text