-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidator_test.go
More file actions
309 lines (234 loc) · 6.93 KB
/
validator_test.go
File metadata and controls
309 lines (234 loc) · 6.93 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package validator
import (
"reflect"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)
func init() {
SetupOptions(func(opts *ValidationOptions) {
opts.ExposeEnumValues = true
opts.ExposeValidatorNames = true
opts.NoPanicOnFunctionConflict = true
})
}
func assertNull(t *testing.T, value interface{}, msg ...string) {
assert.Nil(t, value, msg)
}
func assertFalse(t *testing.T, value bool, msg ...string) {
assert.False(t, value, msg)
}
func assertTrue(t *testing.T, value bool, msg ...string) {
assert.True(t, value, msg)
}
func assertEqual(t *testing.T, expected, actual interface{}, msg ...string) {
assert.Equal(t, expected, actual, msg)
}
func TestValidator(t *testing.T) {
type MyStruct struct {
Name string `filter:"trim"`
Age int `validator:"required|min(21)|max(35)"`
}
myStruct := MyStruct{Age: 21, Name: " John Doe "}
res := Validate(&myStruct)
assertEqual(t, myStruct.Name, "John Doe")
assertTrue(t, res.IsValid(), "Validation failed")
}
func TestCustomFunctions(t *testing.T) {
type MyStruct struct {
Name string `filter:"trim|upper"`
Age int `validator:"range(10,50)" filter:"square|square"`
}
myStruct := MyStruct{Age: 20, Name: " John Doe "}
// install custom validator function
AddValidator("range", func(ctx *ValidationContext) bool {
if ctx.ArgCount() != 2 {
// instead of panicking, we can simply return an api-level error message
ctx.ErrorMessage = "range function requires exactly two parameters"
return false
}
min := ctx.MustGetIntArg(0)
max := ctx.MustGetIntArg(1)
if ctx.IsNull {
return false
}
value := ctx.GetValue().Int()
if value >= min && value <= max {
return true
}
ctx.ErrorMessage = "value must be between " + strconv.FormatInt(min, 10) + " and " + strconv.FormatInt(max, 10)
return false
})
// this filter converts the given string to upper case
AddFilter("upper", func(ctx *ValidationContext) reflect.Value {
ctx.ValueMustBeOfKind(reflect.String)
// the filter is aware of pointers
if !ctx.IsNull {
value := ctx.GetValue().String()
return reflect.ValueOf(strings.ToUpper(value))
}
// simply return what's alreay there
return ctx.GetValue()
})
// this filter squares the given int value
AddFilter("square", func(ctx *ValidationContext) reflect.Value {
ctx.ValueMustBeOfKind(reflect.Int)
// the filter is aware of pointers
if !ctx.IsNull {
value := int(ctx.GetValue().Int())
value = value * value
return reflect.ValueOf(value)
}
// simply return what's alreay there
return ctx.GetValue()
})
res := Validate(&myStruct)
assertEqual(t, myStruct.Name, "JOHN DOE")
assertEqual(t, myStruct.Age, 160000)
assertTrue(t, res.IsValid(), "Validation failed")
}
func TestPointer(t *testing.T) {
age := int(42)
name := " Bames Jond "
type MyStruct struct {
Name *string `filter:"trim|upper"`
Age *int `validator:"min(50)" filter:"square" label:"Agent age"`
}
myStruct := MyStruct{Age: &age, Name: &name}
AddFilter("upper", func(ctx *ValidationContext) reflect.Value {
ctx.ValueMustBeOfKind(reflect.String)
// the filter is aware of pointers
if ctx.IsPointer && !ctx.IsNull {
value := strings.ToUpper(ctx.GetValue().String())
return reflect.ValueOf(&value)
}
// simply return what's alreay there
return ctx.GetValue()
})
AddFilter("square", func(ctx *ValidationContext) reflect.Value {
ctx.ValueMustBeOfKind(reflect.Int)
// the filter is aware of pointers
if ctx.IsPointer && !ctx.IsNull {
value := int(ctx.GetValue().Int())
value = value * value
return reflect.ValueOf(&value)
}
// simply return what's alreay there
return ctx.GetValue()
})
res := Validate(&myStruct)
assertEqual(t, *myStruct.Name, "BAMES JOND")
assertEqual(t, *myStruct.Age, 1764)
assertFalse(t, res.IsValid(), "Validation failed")
}
func TestEnum(t *testing.T) {
type MyEnum int
const (
Opt1 MyEnum = iota
Opt2 MyEnum = iota
)
type MyStruct struct {
EnumValue *MyEnum `validator:"required|enum(0,1)"`
}
opt := Opt2
myStruct := MyStruct{EnumValue: &opt}
res := Validate(&myStruct)
// fmt.Println(res)
assertEqual(t, *myStruct.EnumValue, Opt2)
assertTrue(t, res.IsValid(), "Validation failed")
}
func TestOptional(t *testing.T) {
type MyStruct struct {
Optional *string `validator:"min(10)|max(20)"`
}
myStruct := MyStruct{Optional: nil}
res := Validate(&myStruct)
// fmt.Println(res)
assertTrue(t, res.IsValid(), "Validation failed")
}
func TestRequired(t *testing.T) {
type MyStruct struct {
Optional *string `validator:"required|min(10)|max(20)"`
}
myStruct := MyStruct{Optional: nil}
res := Validate(&myStruct)
// fmt.Println(res)
assertFalse(t, res.IsValid(), "Validation failed")
}
func TestNested(t *testing.T) {
type struct2 struct {
Age int `validator:"min(18)" message:"must be at least 18 to open an account here"`
}
type Struct1 struct {
struct2
Foo int `validator:"min(100)" label:"Deposit amount"`
}
type MyStruct struct {
Struct1
Bar int `validator:"min(10)|max(20)"`
}
myStruct := MyStruct{Bar: 15}
res := Validate(&myStruct)
// fmt.Println(res)
assertFalse(t, res.IsValid(), "Validation failed")
}
func TestActivationTrigger(t *testing.T) {
type Person struct {
Id int `validator:"min(1000)" message:"Employment ID numbers start at 1000" trigger:"update"`
Age int `filter:"add_five"` // implicit 'all'
Height int `filter:"add_five|add_five" trigger:"create,update"`
}
AddFilter("add_five", func(ctx *ValidationContext) reflect.Value {
ctx.ValueMustBeOfKind(reflect.Int)
if !ctx.IsNull {
value := ctx.GetValue().Int()
value += 5
if ctx.IsPointer {
ctx.GetValue().Set(reflect.ValueOf(&value))
} else {
ctx.GetValue().SetInt(value)
}
}
return ctx.GetValue()
})
person := Person{Id: 0, Age: 2, Height: 1}
// create user
res := Validate(&person, "create")
// fmt.Println(res)
assertEqual(t, person.Id, 0)
assertEqual(t, person.Age, 7)
assertEqual(t, person.Height, 11)
assertTrue(t, res.IsValid(), "Validation failed")
// assign id
person.Id = 999
// update user
res = Validate(&person, "update")
// fmt.Println(res)
assertEqual(t, person.Id, 999)
assertEqual(t, person.Age, 12) //---\
assertEqual(t, person.Height, 21) // ------> opts.StopOnFirstError = false
assertFalse(t, res.IsValid(), "Validation failed")
}
func TestNullIfEmpty(t *testing.T) {
type Form struct {
Username *string `validator:"alphanum" filter:"trim|null_if_empty"`
}
name := ""
form := Form{Username: &name}
r := Validate(&form)
assertTrue(t, r.IsValid(), "validation failed")
assertNull(t, form.Username)
}
func TestEmptyAsNull(t *testing.T) {
type Form struct {
FirstName *string `validator:"min(10)" flags:"allow_zero"`
LastName *string `validator:"min(10)" flags:"allow_zero"`
}
name := ""
form := Form{LastName: &name}
r := Validate(&form)
assertTrue(t, r.IsValid(), "validation failed")
assertNull(t, form.FirstName, "Expected null")
assertEqual(t, *form.LastName, "", "Expected null")
}