Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
198 lines (182 loc) · 4.94 KB
/
Copy pathexample_test.go
File metadata and controls
198 lines (182 loc) · 4.94 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package validator_test
import (
"context"
"errors"
"fmt"
"net/url"
"reflect"
"strings"
"github.com/libtnb/validator"
)
func Example() {
type User struct {
Email string `validate:"required && email"`
Age int `validate:"required && gte:18"`
}
vd := validator.MustStruct(User{Email: "a@b.com", Age: 20})
_ = vd.Validate(context.Background())
fmt.Println("valid:", !vd.Fails())
// Output: valid: true
}
func ExampleStruct() {
type User struct {
Email string `validate:"required && email"`
Age int `validate:"required && gte:18"`
}
vd, err := validator.Struct(User{Email: "not-an-email", Age: 17})
if err != nil {
panic(err) // not a struct, or a tag that does not compile
}
err = vd.Validate(context.Background())
errs, _ := validator.AsErrors(err)
fmt.Println(errs.OneFor("Email"))
fmt.Println(errs.OneFor("Age"))
// Output:
// The Email must be a valid email address.
// The Age field must be greater than or equal to 18.
}
func ExampleValid() {
type User struct {
Name string `validate:"required && alpha"`
}
ok, err := validator.Valid(context.Background(), User{Name: "alice"})
fmt.Println(ok, err)
// Output: true <nil>
}
func ExampleMap() {
vd := validator.MustMap(
map[string]any{"name": "alice", "role": "root"},
map[string]string{
"name": "required && alpha",
"role": "required && in:admin,user",
},
)
_ = vd.Validate(context.Background())
fmt.Println(vd.Errors().OneFor("role"))
// Output: The selected role is invalid.
}
func ExampleValidator_Map() {
v := validator.MustNew()
vd := v.MustMap(
map[string]any{"name": "alice"},
// boolean DSL: AND-grouped OR
map[string]string{"name": "required && (alpha || in:bob,carol)"},
)
_ = vd.Validate(context.Background())
fmt.Println("valid:", !vd.Fails())
// Output: valid: true
}
func ExampleJSON() {
vd := validator.MustJSON(`{"name": "alice", "age": 17}`, map[string]string{
"name": "required && alpha",
"age": "required && gte:18",
})
err := vd.Validate(context.Background())
fmt.Println(err)
// Output: age: The age field must be greater than or equal to 18.
}
func ExampleValues() {
type Form struct {
Name string `json:"name"`
Tags []string `json:"tags"`
}
// Name fields after their json tag so form keys and struct fields match.
v := validator.MustNew(validator.WithTagNameFunc(func(f reflect.StructField) string {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
return name
}))
// tags=go&tags=web: a repeated key becomes a []string, so dive checks each value.
form := url.Values{"name": {"alice"}, "tags": {"go", "web"}}
vd := v.MustValues(form, map[string]string{
"name": "required && alpha",
"tags": "required && dive && alpha",
})
var f Form
if err := vd.ValidateAs(context.Background(), &f); err != nil {
fmt.Println(err)
return
}
fmt.Println(f.Name, f.Tags)
// Output: alice [go web]
}
func ExampleValue() {
vd := validator.MustValue("nope", "required && email")
_ = vd.Validate(context.Background())
fmt.Println(vd.Fails())
// Output: true
}
func ExampleValidation_ValidateAs() {
type User struct {
Email string `validate:"required && email"`
Age int `validate:"required && numeric"`
}
vd := validator.MustMap(
map[string]any{"Email": "a@b.com", "Age": "42"},
map[string]string{"Email": "required && email", "Age": "required && numeric"},
)
_ = vd.Validate(context.Background())
var u User
if err := vd.ValidateAs(context.Background(), &u); err == nil {
fmt.Printf("%s / %d\n", u.Email, u.Age)
}
// Output: a@b.com / 42
}
func ExampleValidation_AddFilters() {
type Form struct {
Email string
}
vd := validator.MustMap(
map[string]any{"Email": " Alice@Example.com "},
map[string]string{"Email": "required && email"},
)
// Filters run before the rules; ValidateAs binds the filtered value.
_ = vd.AddFilters("Email", "trim|lower")
var f Form
if err := vd.ValidateAs(context.Background(), &f); err != nil {
fmt.Println(err)
return
}
fmt.Println(f.Email)
// Output: alice@example.com
}
func ExampleWithRuleFunc() {
v := validator.MustNew(validator.WithRuleFunc(
"even",
func(f *validator.Field) bool {
n, ok := f.Value[int]()
return ok && n%2 == 0
},
"The {field} must be even.",
))
vd := v.MustValue(3, "required && even")
_ = vd.Validate(context.Background())
fmt.Println(vd.Errors().One())
// Output: The value must be even.
}
func ExampleCheck() {
type Signup struct {
Email string `validate:"required && emial"` // typo
}
err := validator.Check[Signup]()
fmt.Println(errors.Is(err, validator.ErrInvalidRules))
var rulesErr *validator.RulesError
if errors.As(err, &rulesErr) {
fmt.Println(rulesErr.Field)
}
// Output:
// true
// Email
}
func ExampleDescribe() {
type User struct {
Name string `validate:"required && min:3"`
Tags []string `validate:"dive && alpha"`
}
fields, _ := validator.Describe[User]()
for _, f := range fields {
fmt.Println(f.Name, f.Rules, f.Element)
}
// Output:
// Name [{required []} {min [3]}] []
// Tags [] [{alpha []}]
}