-
Notifications
You must be signed in to change notification settings - Fork 0
/
validating.go
603 lines (523 loc) · 14.8 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
package validate
import (
"reflect"
"strings"
)
// const requiredValidator = "required"
// the validating 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()
}
// ValidateErr do validate processing and return error
func (v *Validation) ValidateErr(scene ...string) error {
if v.Validate(scene...) {
return nil
}
return v.Errors
}
// ValidateE do validate processing and return Errors
//
// NOTE: need use len() to check the return is empty or not.
func (v *Validation) ValidateE(scene ...string) Errors {
if v.Validate(scene...) {
return nil
}
return v.Errors
}
// Validate processing
func (v *Validation) Validate(scene ...string) bool {
// has been validated OR has error
if v.hasValidated || v.shouldStop() {
return v.IsSuccess()
}
// release instance to pool TODO
// defer func() {
// v.resetRules()
// vPool.Put(v)
// }()
// init scene info
v.SetScene(scene...)
v.sceneFields = v.sceneFieldMap()
// apply filter rules before validate.
// if !v.Filtering() && v.StopOnError {
// return false
// }
// // apply rule to validate data.
// for _, rule := range v.rules {
// if rule.Apply(v) {
// break
// }
// }
// modified
// Customization: Alter the sequence of validating data and filtering data; because filtering filters incorrect data so validation would not generate error for incorrect data.
// apply rule to validate data.
for _, rule := range v.rules {
if rule.Apply(v) {
break
}
}
// apply filter rules.
if false == v.Filtering() && v.StopOnError {
return false
}
v.hasValidated = true
if v.hasError { // clear safe data on error.
v.SaferData = make(map[string]any)
}
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.SaferData[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
}
// Todo: Update validation and filtering flow
if val != nil{
// Customization: We need to bind all data
v.SaferData[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) {
if val != nil {
v.SaferData[field] = val // save validated value.
}
} else { // build and collect error message
v.AddError(field, r.validator, r.errorMessage(field, r.validator, v))
}
// Customization: To validate all the fields we need to continue iterating rather stopping on single error.
// 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
}
ss := make([]string, 0, len(r.arguments))
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
}
// value by tryGet(key) TODO
type value struct {
val any
key string
// has dot-star ".*" in the key. eg: details.sub.*.field
dotStar bool
// last index of dot-star on the key. eg: details.sub.*.field, lastIdx=11
lastIdx int
// is required or requiredXX check
require bool
}
// validate the field value
//
// - field: the field name. eg: "name", "details.sub.*.field"
// - name: the validator name. eg: "required", "min"
func (r *Rule) valueValidate(field, name string, val any, v *Validation) (ok bool) {
// "-" OR "safe" mark field value always is safe.
if name == RuleSafe1 || name == RuleSafe {
return true
}
// support check sub element in a slice list. eg: field=top.user.*.name
dotStarNum := strings.Count(field, ".*")
// perf: The most commonly used rule "required" - direct call v.Required()
if name == RuleRequired && dotStarNum == 0 {
return v.Required(field, val)
}
// call value validator in the rule.
fm := r.checkFuncMeta
if fm == nil {
// fallback: get validator from 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
// check arg num is match, need exclude "requiredXXX"
if r.nameNotRequired {
//noinspection GoNilness
fm.checkArgNum(argNum, r.validator)
}
// 1. args data type convert
args := r.arguments
if ok = convertArgsType(v, fm, field, args); !ok {
return false
}
ft := fm.fv.Type() // type of check func
arg0Kind := ft.In(0).Kind()
// rftVal := reflect.Indirect(reflect.ValueOf(val))
rftVal := reflect.ValueOf(val)
valKind := rftVal.Kind()
if valKind == reflect.Slice && dotStarNum > 0 {
sliceLen, sliceCap := rftVal.Len(), rftVal.Cap()
// if dotStarNum > 1, need flatten multi level slice with depth=dotStarNum.
if dotStarNum > 1 {
rftVal = flatSlice(rftVal, dotStarNum-1)
sliceLen, sliceCap = rftVal.Len(), rftVal.Cap()
}
// check requiredXX validate - flatten multi level slice, count ".*" number.
// TIP: if len < cap: not enough elements in the slice. use empty val call validator.
if !r.nameNotRequired && sliceLen < sliceCap {
return callValidator(v, fm, field, nil, r.arguments)
}
var subVal any
// check each element in the slice.
for i := 0; i < sliceLen; i++ {
subRv := indirectInterface(rftVal.Index(i))
subKind := subRv.Kind()
// 1.1 convert field value type, is func first argument.
if r.nameNotRequired && arg0Kind != reflect.Interface && arg0Kind != subKind {
subVal, ok = convValAsFuncArg0Type(arg0Kind, subKind, subRv.Interface())
if !ok {
v.convArgTypeError(field, fm.name, subKind, arg0Kind, 0)
return false
}
} else {
if subRv.IsValid() {
subVal = subRv.Interface()
} else {
subVal = nil
}
}
// 2. call built in validator
if !callValidator(v, fm, field, subVal, r.arguments) {
return false
}
}
return true
}
// 1 convert field value type, is func first argument.
if r.nameNotRequired && arg0Kind != reflect.Interface && arg0Kind != valKind {
val, ok = convValAsFuncArg0Type(arg0Kind, valKind, val)
if !ok {
v.convArgTypeError(field, fm.name, valKind, arg0Kind, 0)
return false
}
}
// 2. call built in validator
return callValidator(v, fm, field, val, r.arguments)
}
// convert input field value type, is validator func first argument.
func convValAsFuncArg0Type(arg0Kind, valKind reflect.Kind, val any) (any, bool) {
// If the validator function does not expect a pointer, but the value is a pointer,
// dereference the value.
if arg0Kind != reflect.Ptr && valKind == reflect.Ptr {
if val == nil {
return nil, true
}
val = reflect.ValueOf(val).Elem().Interface()
valKind = reflect.TypeOf(val).Kind()
}
// ak, err := basicKind(rftVal)
bk, err := basicKindV2(valKind)
if err != nil {
return nil, false
}
// manual converted
if nVal, _ := convTypeByBaseKind(val, bk, arg0Kind); nVal != nil {
return nVal, true
}
// TODO return nil, false
return val, true
}
func callValidator(v *Validation, fm *funcMeta, field string, val any, args []any) (ok bool) {
// use `switch` can avoid using reflection to call methods and improve speed
// fm.name please see pkg var: validatorValues
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])
case "gt":
ok = Gt(val, args[0])
case "min":
ok = Min(val, args[0])
case "max":
ok = Max(val, args[0])
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))
case "isSlice":
ok = IsSlice(val)
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 []any) (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))
}
// only one args and type is any
if lastArgIndex == 1 && lastTyp == reflect.Interface {
return true
}
var wantKind 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
argVKind := av.Kind()
// Notice: "+1" because first arg is field-value, need exclude it.
if fm.isVariadic && i+1 >= lastArgIndex {
if lastTyp == argVKind { // type is same
continue
}
ak, err := basicKindV2(argVKind)
if err != nil {
v.convArgTypeError(field, fm.name, argVKind, wantKind, fcArgIndex)
return
}
// manual converted
if nVal, _ := convTypeByBaseKind(args[i], ak, lastTyp); nVal != nil {
args[i] = nVal
continue
}
// unable to convert
v.convArgTypeError(field, fm.name, argVKind, wantKind, fcArgIndex)
return
}
// "+1" because func first arg is val, need skip it.
argIType := ft.In(fcArgIndex)
wantKind = argIType.Kind()
// type is same. or want type is interface
if wantKind == argVKind || wantKind == reflect.Interface {
continue
}
ak, err := basicKindV2(argVKind)
if err != nil {
v.convArgTypeError(field, fm.name, argVKind, wantKind, fcArgIndex)
return
}
// can auto convert type.
if av.Type().ConvertibleTo(argIType) {
args[i] = av.Convert(argIType).Interface()
} else if nVal, _ := convTypeByBaseKind(args[i], ak, wantKind); nVal != nil { // manual converted
args[i] = nVal
} else { // unable to convert
v.convArgTypeError(field, fm.name, argVKind, wantKind, fcArgIndex)
return
}
}
return true
}
func callValidatorValue(fv reflect.Value, val any, args []any) bool {
// build params for the validator func.
argNum := len(args)
argIn := make([]reflect.Value, argNum+1)
// if val is any(nil): rftVal.IsValid()==false
// if val is typed(nil): rftVal.IsValid()==true
rftVal := reflect.ValueOf(val)
// fix: #125 fv.Call() will panic on rftVal.Kind() is Invalid
if !rftVal.IsValid() {
rftVal = nilRVal
}
// Add this check to handle pointer values
if rftVal.Kind() == reflect.Ptr && !rftVal.IsNil() {
rftVal = rftVal.Elem()
}
argIn[0] = rftVal
for i := 0; i < argNum; i++ {
rftValA := reflect.ValueOf(args[i])
if !rftValA.IsValid() {
rftValA = nilRVal
}
argIn[i+1] = rftValA
}
// TODO panic recover, refer the text/template/funcs.go
// defer func() {
// if r := recover(); r != nil {
// if e, ok := r.(error); ok {
// err = e
// } else {
// err = fmt.Errorf("%v", r)
// }
// }
// }()
// NOTICE: f.CallSlice()与Call() 不一样的是,CallSlice参数的最后一个会被展开
// vs := fv.Call(argIn)
return fv.Call(argIn)[0].Bool()
}