forked from gookit/validate
/
validating.go
435 lines (376 loc) · 10.3 KB
/
validating.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package validate
import (
"reflect"
)
// const requiredValidator = "required"
// the validate result status:
// 0 ok 1 skip 2 fail
const (
statusOk uint8 = iota
statusSkip
statusFail
)
/*************************************************************
* Do Validating
*************************************************************/
// ValidateData validate given data-source
func (v *Validation) ValidateData(data DataFace) bool {
v.data = data
return v.Validate()
}
// Validate processing
func (v *Validation) Validate(scene ...string) bool {
// has been validated OR has error
if v.hasValidated || v.shouldStop() {
return v.IsSuccess()
}
// init scene info
v.SetScene(scene...)
v.sceneFields = v.sceneFieldMap()
// apply filter rules before validate.
if false == v.Filtering() && v.StopOnError {
return false
}
// apply rule to validate data.
for _, rule := range v.rules {
if rule.Apply(v) {
break
}
}
v.hasValidated = true
if v.hasError {
// clear safe data on error.
v.safeData = make(map[string]interface{})
}
return v.IsSuccess()
}
// Apply current rule for the rule fields
func (r *Rule) Apply(v *Validation) (stop bool) {
// scene name is not match. skip the rule
if r.scene != "" && r.scene != v.scene {
return
}
// has beforeFunc and it return FALSE, skip validate
if r.beforeFunc != nil && !r.beforeFunc(v) {
return
}
var err error
// get real validator name
name := r.realName
// validator name is not "required"
isNotRequired := r.nameNotRequired
// validate each field
for _, field := range r.fields {
if v.isNotNeedToCheck(field) {
continue
}
// uploaded file validate
if isFileValidator(name) {
status := r.fileValidate(field, name, v)
if status == statusFail {
// build and collect error message
v.AddError(field, r.validator, r.errorMessage(field, r.validator, v))
if v.StopOnError {
return true
}
}
continue
}
// get field value. val, exist := v.Get(field)
val, exist, isDefault := v.GetWithDefault(field)
// not exists but has default value
if isDefault {
// update source data field value and re-set value
val, err := v.updateValue(field, val)
if err != nil {
// panicf(err.Error())
v.AddErrorf(field, err.Error())
if v.StopOnError {
return true
}
continue
}
// dont need check default value
if !v.CheckDefault {
// save validated value.
v.safeData[field] = val
continue
}
// go on check custom default value
exist = true
} else if r.optional { // r.optional=true. skip check.
continue
}
// apply filter func.
if exist && r.filterFunc != nil {
if val, err = r.filterFunc(val); err != nil { // has error
v.AddError(filterError, filterError, err.Error())
return true
}
// update source field value
newVal, err := v.updateValue(field, val)
if err != nil {
// panicf(err.Error())
v.AddErrorf(field, err.Error())
if v.StopOnError {
return true
}
continue
}
// re-set value
val = newVal
// save filtered value.
v.filteredData[field] = val
}
// empty value AND skip on empty.
if r.skipEmpty && isNotRequired && IsEmpty(val) {
continue
}
// validate field value
if r.valueValidate(field, name, val, v) {
v.safeData[field] = val // save validated value.
} else { // build and collect error message
v.AddError(field, r.validator, r.errorMessage(field, r.validator, v))
}
// stop on error
if v.shouldStop() {
return true
}
}
return false
}
func (r *Rule) fileValidate(field, name string, v *Validation) uint8 {
// check data source
form, ok := v.data.(*FormData)
if !ok {
return statusFail
}
// skip on empty AND field not exist
if r.skipEmpty && !form.HasFile(field) {
return statusSkip
}
var ss []string
for _, item := range r.arguments {
ss = append(ss, item.(string))
}
switch name {
case "isFile":
ok = v.IsFormFile(form, field)
case "isImage":
ok = v.IsFormImage(form, field, ss...)
case "inMimeTypes":
if ln := len(ss); ln == 0 {
panicf("not enough parameters for validator '%s'!", r.validator)
} else if ln == 1 {
//noinspection GoNilness
ok = v.InMimeTypes(form, field, ss[0])
} else { // ln > 1
//noinspection GoNilness
ok = v.InMimeTypes(form, field, ss[0], ss[1:]...)
}
}
if ok {
return statusOk
}
return statusFail
}
// validate the field value
func (r *Rule) valueValidate(field, name string, val interface{}, v *Validation) bool {
// "-" OR "safe" mark field value always is safe.
if name == "-" || name == "safe" {
return true
}
// call custom validator in the rule.
fm := r.checkFuncMeta
if fm == nil {
// get validator for global or validation
fm = v.validatorMeta(name)
if fm == nil {
panicf("the validator '%s' does not exist", r.validator)
}
}
// some prepare and check.
argNum := len(r.arguments) + 1 // "+1" is the "val" position
rftVal := reflect.ValueOf(val)
valKind := rftVal.Kind()
// check arg num is match, need exclude "requiredXXX"
if r.nameNotRequired {
//noinspection GoNilness
fm.checkArgNum(argNum, r.validator)
//noinspection GoNilness
ft := fm.fv.Type()
// convert field val type, is first argument.
firstTyp := ft.In(0).Kind()
if firstTyp != valKind && firstTyp != reflect.Interface {
ak, err := basicKind(rftVal)
if err != nil { // todo check?
//noinspection GoNilness
v.convArgTypeError(field, fm.name, valKind, firstTyp, 0)
return false
}
// manual converted
if nVal, _ := convertType(val, ak, firstTyp); nVal != nil {
val = nVal
}
}
}
// 1. args data type convert
args := r.arguments
if ok := convertArgsType(v, fm, field, args); !ok {
return false
}
// 2. call built in validators
return callValidator(v, fm, field, val, r.arguments)
}
func callValidator(v *Validation, fm *funcMeta, field string, val interface{}, args []interface{}) (ok bool) {
// use `switch` can avoid using reflection to call methods and improve speed
switch fm.name {
case "required":
ok = v.Required(field, val)
case "requiredIf":
ok = v.RequiredIf(field, val, args2strings(args)...)
case "requiredUnless":
ok = v.RequiredUnless(field, val, args2strings(args)...)
case "requiredWith":
ok = v.RequiredWith(field, val, args2strings(args)...)
case "requiredWithAll":
ok = v.RequiredWithAll(field, val, args2strings(args)...)
case "requiredWithout":
ok = v.RequiredWithout(field, val, args2strings(args)...)
case "requiredWithoutAll":
ok = v.RequiredWithoutAll(field, val, args2strings(args)...)
case "lt":
ok = Lt(val, args[0].(int64))
case "gt":
ok = Gt(val, args[0].(int64))
case "min":
ok = Min(val, args[0].(int64))
case "max":
ok = Max(val, args[0].(int64))
case "enum":
ok = Enum(val, args[0])
case "notIn":
ok = NotIn(val, args[0])
case "isInt":
if argLn := len(args); argLn == 0 {
ok = IsInt(val)
} else if argLn == 1 {
ok = IsInt(val, args[0].(int64))
} else { // argLn == 2
ok = IsInt(val, args[0].(int64), args[1].(int64))
}
case "isString":
if argLn := len(args); argLn == 0 {
ok = IsString(val)
} else if argLn == 1 {
ok = IsString(val, args[0].(int))
} else { // argLn == 2
ok = IsString(val, args[0].(int), args[1].(int))
}
case "isNumber":
ok = IsNumber(val)
case "isStringNumber":
ok = IsStringNumber(val.(string))
case "length":
ok = Length(val, args[0].(int))
case "minLength":
ok = MinLength(val, args[0].(int))
case "maxLength":
ok = MaxLength(val, args[0].(int))
case "stringLength":
if argLn := len(args); argLn == 1 {
ok = RuneLength(val, args[0].(int))
} else if argLn == 2 {
ok = RuneLength(val, args[0].(int), args[1].(int))
}
case "regexp":
ok = Regexp(val.(string), args[0].(string))
case "between":
ok = Between(val, args[0].(int64), args[1].(int64))
case "isJSON":
ok = IsJSON(val.(string))
default:
// 3. call user custom validators, will call by reflect
ok = callValidatorValue(fm.fv, val, args)
}
return
}
// convert args data type
func convertArgsType(v *Validation, fm *funcMeta, field string, args []interface{}) (ok bool) {
if len(args) == 0 {
return true
}
ft := fm.fv.Type()
lastTyp := reflect.Invalid
lastArgIndex := fm.numIn - 1
// fix: isVariadic == true. last arg always is slice.
// eg. "...int64" -> slice "[]int64"
if fm.isVariadic {
// get variadic kind. "[]int64" -> reflect.Int64
lastTyp = getVariadicKind(ft.In(lastArgIndex).String())
}
// only one args and it type is interface{}
if lastArgIndex == 1 && lastTyp == reflect.Interface {
return true
}
var wantTyp reflect.Kind
// convert args data type
for i, arg := range args {
av := reflect.ValueOf(arg)
// index in the func
// "+1" because func first arg is `val`, need skip it.
fcArgIndex := i + 1
// Notice: "+1" because first arg is field-value, need exclude it.
if fm.isVariadic && i+1 >= lastArgIndex {
if lastTyp == av.Kind() { // type is same
continue
}
ak, err := basicKind(av)
if err != nil {
v.convArgTypeError(field, fm.name, av.Kind(), wantTyp, fcArgIndex)
return
}
// manual converted
if nVal, _ := convertType(args[i], ak, lastTyp); nVal != nil {
args[i] = nVal
continue
}
// unable to convert
v.convArgTypeError(field, fm.name, av.Kind(), wantTyp, fcArgIndex)
return
}
// "+1" because func first arg is val, need skip it.
argITyp := ft.In(fcArgIndex)
wantTyp = argITyp.Kind()
// type is same. or want type is interface
if wantTyp == av.Kind() || wantTyp == reflect.Interface {
continue
}
ak, err := basicKind(av)
if err != nil {
v.convArgTypeError(field, fm.name, av.Kind(), wantTyp, fcArgIndex)
return
}
if av.Type().ConvertibleTo(argITyp) { // can auto convert type.
args[i] = av.Convert(argITyp).Interface()
} else if nVal, _ := convertType(args[i], ak, wantTyp); nVal != nil { // manual converted
args[i] = nVal
} else { // unable to convert
v.convArgTypeError(field, fm.name, av.Kind(), wantTyp, fcArgIndex)
return
}
}
return true
}
func callValidatorValue(fv reflect.Value, val interface{}, args []interface{}) bool {
argNum := len(args)
// build params for the validator func.
argIn := make([]reflect.Value, argNum+1)
argIn[0] = reflect.ValueOf(val)
for i := 0; i < argNum; i++ {
argIn[i+1] = reflect.ValueOf(args[i])
}
// NOTICE: f.CallSlice()与Call() 不一样的是,CallSlice参数的最后一个会被展开
// vs := fv.Call(argIn)
return fv.Call(argIn)[0].Bool()
}