-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
93 lines (78 loc) · 1.72 KB
/
example_test.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package validator_test
import (
"context"
"fmt"
"github.com/utahta/go-validator"
)
func ExampleValidateStruct_simple() {
type user struct {
Name string `valid:"required,alphanum"`
Age uint `valid:"required,len(0|116)"`
Email string `valid:"optional,email"`
}
v := validator.New()
err := v.ValidateStruct(&user{
Name: "gopher",
Age: 9,
Email: "",
})
fmt.Println(err)
err = v.ValidateStruct(&user{
Name: "_",
Age: 200,
Email: "invalid",
})
fmt.Println(err)
// Output:
// <nil>
// Name: '_' does validate as 'alphanum';Age: '200' does validate as 'len(0|116)';Email: 'invalid' does validate as 'email'
}
func ExampleValidateStruct_setFunc() {
type content struct {
Type string `valid:"contentType(image/jpeg|image/png|image/gif)"`
}
v := validator.New(
validator.WithFunc("contentType", func(_ context.Context, f validator.Field, opt validator.FuncOption) (bool, error) {
v := f.Value().String()
for _, param := range opt.TagParams {
if v == param {
return true, nil
}
}
return false, nil
}),
)
err := v.ValidateStruct(&content{
Type: "image/jpeg",
})
fmt.Println(err)
err = v.ValidateStruct(&content{
Type: "image/bmp",
})
fmt.Println(err)
// Output:
// <nil>
// Type: 'image/bmp' does validate as 'contentType(image/jpeg|image/png|image/gif)'
}
func ExampleValidateStruct_or() {
type user struct {
ID string `valid:"or(alpha|numeric)"`
}
v := validator.New()
err := v.ValidateStruct(&user{
ID: "abc",
})
fmt.Println(err)
err = v.ValidateStruct(&user{
ID: "123",
})
fmt.Println(err)
err = v.ValidateStruct(&user{
ID: "abc123",
})
fmt.Println(err)
// Output:
// <nil>
// <nil>
// ID: 'abc123' does validate as 'or(alpha|numeric)'
}