-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathvalidator.go
More file actions
2818 lines (2496 loc) · 87.9 KB
/
Copy pathvalidator.go
File metadata and controls
2818 lines (2496 loc) · 87.9 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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package validator
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
)
// regexCache stores compiled regular expressions to avoid recompilation
var regexCache sync.Map // map[string]*regexp.Regexp
// Reusable zero-size map value for set-style reflect maps (e.g. isDistinct).
var (
emptyStructType = reflect.TypeOf(struct{}{})
emptyStructValue = reflect.ValueOf(struct{}{})
)
// getCompiledRegex returns a cached compiled regex or compiles and caches it.
// Uses LoadOrStore pattern to handle concurrent access correctly.
func getCompiledRegex(pattern string) (*regexp.Regexp, error) {
// Fast path: check if already cached
if cached, ok := regexCache.Load(pattern); ok {
return cached.(*regexp.Regexp), nil
}
// Slow path: compile and store
re, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
// Use LoadOrStore to handle race condition - if another goroutine
// stored the same pattern concurrently, use that one instead
actual, _ := regexCache.LoadOrStore(pattern, re)
return actual.(*regexp.Regexp), nil
}
// defaultBufferCap is the default capacity for pooled byte buffers
const defaultBufferCap = 128
// maxBufferCap prevents unbounded buffer growth in the pool
const maxBufferCap = 1024
// byteBufferPool provides reusable byte buffers to reduce allocations
var byteBufferPool = sync.Pool{
New: func() any {
buf := make([]byte, 0, defaultBufferCap)
return &buf
},
}
// getBuffer gets a buffer from the pool
func getBuffer() *[]byte {
return byteBufferPool.Get().(*[]byte)
}
// putBuffer returns a buffer to the pool.
// Buffers that grew too large are discarded to prevent memory bloat.
func putBuffer(buf *[]byte) {
// Discard buffers that grew too large to prevent memory bloat
if cap(*buf) > maxBufferCap {
return
}
*buf = (*buf)[:0]
byteBufferPool.Put(buf)
}
// appendNamespace returns a fresh namespace of the form base + part + ".".
// It always allocates a new backing array so sibling fields can never corrupt
// each other's paths through append-aliasing of a shared base slice.
func appendNamespace(base, part []byte) []byte {
out := make([]byte, 0, len(base)+len(part)+1)
out = append(out, base...)
out = append(out, part...)
out = append(out, '.')
return out
}
// buildFieldName efficiently builds a field name string
func buildFieldName(namespace, fieldName []byte) string {
if len(namespace) == 0 {
return string(fieldName)
}
buf := getBuffer()
*buf = append(*buf, namespace...)
*buf = append(*buf, fieldName...)
result := string(*buf)
putBuffer(buf)
return result
}
// =============================================================================
// Helper Functions - Reduce code duplication and improve performance
// =============================================================================
// deref dereferences interface and pointer values to their underlying value.
// This consolidates the repeated pattern found 30+ times in the codebase.
func deref(v reflect.Value) reflect.Value {
for v.Kind() == reflect.Interface || v.Kind() == reflect.Pointer {
if v.IsNil() {
return v
}
v = v.Elem()
}
return v
}
// comparisonOp represents a comparison operator
type comparisonOp string
const (
opGt comparisonOp = ">"
opGte comparisonOp = ">="
opLt comparisonOp = "<"
opLte comparisonOp = "<="
opEq comparisonOp = "=="
)
// compareValue is a unified comparison function that handles all numeric types.
// This replaces the duplicated switch statements in isMin, isMax, isGt, isGte, isLt, isLte.
func compareValue(v reflect.Value, params []string, op comparisonOp, ruleName string) (bool, error) {
if len(params) == 0 {
return false, fmt.Errorf("validator: %s rule requires at least one parameter", ruleName)
}
// Check for decimal.Decimal type first
if d, ok := asDecimal(v); ok {
p, _, err := parseDecimalParams(params)
if err != nil {
return false, fmt.Errorf("validator: %s decimal: %w", ruleName, err)
}
switch op {
case opGt:
return IsDecimalGt(d, p), nil
case opGte:
return IsDecimalGte(d, p), nil
case opLt:
return IsDecimalLt(d, p), nil
case opLte:
return IsDecimalLte(d, p), nil
case opEq:
return IsDecimalEqual(d, p), nil
}
}
switch v.Kind() {
case reflect.String:
p, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for %s rule on string field: %w", ruleName, err)
}
return compareString(v.String(), p, string(op))
case reflect.Slice, reflect.Map, reflect.Array:
p, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for %s rule on collection field: %w", ruleName, err)
}
return compareInt64(int64(v.Len()), p, string(op))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for %s rule on int field: %w", ruleName, err)
}
return compareInt64(v.Int(), p, string(op))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p, err := ToUint(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for %s rule on uint field: %w", ruleName, err)
}
return compareUint64(v.Uint(), p, string(op))
case reflect.Float32, reflect.Float64:
p, err := ToFloat(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for %s rule on float field: %w", ruleName, err)
}
return compareFloat64(v.Float(), p, string(op))
default:
return false, fmt.Errorf("validator: %s rule is not supported for type %s", ruleName, v.Kind())
}
}
// compareFields compares two reflect.Value fields with the given operator.
// This consolidates isSame, isLt, isLte, isGt, isGte field comparison functions.
func compareFields(v, anotherField reflect.Value, op comparisonOp, ruleName string) (bool, error) {
if !v.IsValid() || !anotherField.IsValid() {
return false, fmt.Errorf("validator: %s invalid reflection values", ruleName)
}
if v.Kind() != anotherField.Kind() {
return false, fmt.Errorf("validator: %s The two fields must be of the same type %T, %T", ruleName, v.Interface(), anotherField.Interface())
}
// Check for decimal.Decimal type first
if d1, ok := asDecimal(v); ok {
if d2, ok := asDecimal(anotherField); ok {
switch op {
case opGt:
return IsDecimalGt(d1, d2), nil
case opGte:
return IsDecimalGte(d1, d2), nil
case opLt:
return IsDecimalLt(d1, d2), nil
case opLte:
return IsDecimalLte(d1, d2), nil
case opEq:
return IsDecimalEqual(d1, d2), nil
}
}
}
switch v.Kind() {
case reflect.String:
if op == opEq {
return v.String() == anotherField.String(), nil
}
return compareString(v.String(), int64(utf8.RuneCountInString(anotherField.String())), string(op))
case reflect.Slice, reflect.Map, reflect.Array:
return compareInt64(int64(v.Len()), int64(anotherField.Len()), string(op))
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return compareInt64(v.Int(), anotherField.Int(), string(op))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
return compareUint64(v.Uint(), anotherField.Uint(), string(op))
case reflect.Float32, reflect.Float64:
return compareFloat64(v.Float(), anotherField.Float(), string(op))
default:
return false, fmt.Errorf("validator: %s unsupported type %T", ruleName, v.Interface())
}
}
const tagName string = "valid"
// Validator construct
type Validator struct {
Attributes map[string]string
CustomMessage map[string]string
Translator *Translator
// FailFast stops validation at the first field that fails and returns
// immediately, instead of collecting every error. The default (false)
// preserves the collect-all behavior. Set it once at setup, before
// concurrent ValidateStruct calls.
FailFast bool
}
// Default returns a instance of Validator
var Default = New()
// New returns a new instance of Validator
func New() *Validator {
return &Validator{}
}
// isBetween check The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.
//
//nolint:gocyclo,gocritic // Complex validation logic with parameter names
func isBetween(v reflect.Value, params []string) (bool, error) {
if len(params) != 2 {
return false, fmt.Errorf("validator: Between params length must be 2")
}
// Check for decimal.Decimal type first
if d, ok := asDecimal(v); ok {
minVal, maxVal, err := parseDecimalParams(params)
if err != nil {
return false, fmt.Errorf("validator: Between decimal: %w", err)
}
return IsDecimalBetween(d, minVal, maxVal), nil
}
var valid bool
var err error
switch v.Kind() {
case reflect.String:
minVal, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on string field, min value: %w", err)
}
maxVal, err := ToInt(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on string field, max value: %w", err)
}
valid = IsStringBetween(v.String(), minVal, maxVal)
case reflect.Slice, reflect.Map, reflect.Array:
minVal, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on collection field, min value: %w", err)
}
maxVal, err := ToInt(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on collection field, max value: %w", err)
}
valid = IsInt64Between(int64(v.Len()), minVal, maxVal)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
minVal, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, min value: %w", err)
}
maxVal, err := ToInt(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, max value: %w", err)
}
valid = IsInt64Between(v.Int(), minVal, maxVal)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
minVal, err := ToUint(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, min value: %w", err)
}
maxVal, err := ToUint(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, max value: %w", err)
}
valid = IsUint64Between(v.Uint(), minVal, maxVal)
case reflect.Float32, reflect.Float64:
minVal, err := ToFloat(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, min value: %w", err)
}
maxVal, err := ToFloat(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Between rule on numeric field, max value: %w", err)
}
valid = IsFloat64Between(v.Float(), minVal, maxVal)
default:
return false, fmt.Errorf("validator: Between unsupported type %T", v.Interface())
}
return valid, err
}
// createFieldError creates a FieldError struct with common fields populated
func (v *Validator) createFieldError(name, structName, tagName, messageName string, messageParameters MessageParameters, attribute, defaultAttribute, value string, funcError error) *FieldError {
return &FieldError{
Name: name,
StructName: structName,
Tag: tagName,
MessageName: messageName,
MessageParameters: messageParameters,
Attribute: attribute,
DefaultAttribute: defaultAttribute,
Value: value,
FuncError: funcError,
}
}
// isWithRuleMap validates a value using RuleMap and returns formatted error if validation fails
func (v *Validator) validateWithRuleMap(tag *ValidTag, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
if validfunc, ok := RuleMap[tag.name]; ok {
isValid, funcError := validfunc(value)
if !isValid {
return v.formatsMessages(v.createFieldError(
name, structName, tag.name, tag.messageName,
parseValidatorMessageParameters(tag, o),
f.attribute, f.defaultAttribute,
ToString(value.Interface()), funcError,
))
}
}
return nil
}
// isWithParamRuleMap validates a value using ParamRuleMap and returns formatted error if validation fails
func (v *Validator) validateWithParamRuleMap(tag *ValidTag, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
if validfunc, ok := ParamRuleMap[tag.name]; ok {
isValid, funcError := validfunc(value, tag.params)
if !isValid {
return v.formatsMessages(v.createFieldError(
name, structName, tag.name, tag.messageName,
parseValidatorMessageParameters(tag, o),
f.attribute, f.defaultAttribute,
ToString(value.Interface()), funcError,
))
}
}
return nil
}
// isWithStringRulesMap validates a string value using StringRulesMap and returns formatted error if validation fails
func (v *Validator) validateWithStringRulesMap(tag *ValidTag, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
if validfunc, ok := StringRulesMap[tag.name]; ok {
isValid := validfunc(value.String())
if !isValid {
return v.formatsMessages(v.createFieldError(
name, structName, tag.name, tag.messageName,
parseValidatorMessageParameters(tag, o),
f.attribute, f.defaultAttribute,
ToString(value.Interface()), nil,
))
}
}
return nil
}
// isWithStringParamRulesMap validates a string value using StringParamRulesMap and returns formatted error if validation fails
func (v *Validator) validateWithStringParamRulesMap(tag *ValidTag, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
if validfunc, ok := StringParamRulesMap[tag.name]; ok {
isValid := validfunc(value.String(), tag.params)
if !isValid {
return v.formatsMessages(v.createFieldError(
name, structName, tag.name, tag.messageName,
parseValidatorMessageParameters(tag, o),
f.attribute, f.defaultAttribute,
ToString(value.Interface()), nil,
))
}
}
return nil
}
// isFieldComparisonRule reports whether a rule name is a comparison rule that may
// have already been satisfied by dependent field comparison (gt/gte/lt/lte).
func isFieldComparisonRule(name string) bool {
return name == "gt" || name == "gte" || name == "lt" || name == "lte"
}
// applyRuleMaps runs RuleMap then ParamRuleMap for a single tag. ParamRuleMap is
// skipped for comparison rules already handled by dependent field comparison.
func (v *Validator) applyRuleMaps(tag *ValidTag, value reflect.Value, f *field, name, structName string, o reflect.Value, handled bool) error {
if err := v.validateWithRuleMap(tag, value, f, name, structName, o); err != nil {
return err
}
if handled && isFieldComparisonRule(tag.name) {
return nil
}
return v.validateWithParamRuleMap(tag, value, f, name, structName, o)
}
// validateCollectionRules applies dependent rules and RuleMap/ParamRuleMap to a
// map or slice value (without string-specific rules).
func (v *Validator) validateCollectionRules(f *field, value reflect.Value, name, structName string, o reflect.Value) error {
for _, tag := range f.validTags {
handled, err := v.checkDependentRulesWithStatus(tag, f, value, o, name, structName)
if err != nil {
return err
}
if err := v.applyRuleMaps(tag, value, f, name, structName, o, handled); err != nil {
return err
}
}
return nil
}
// isCommonRules applies common validation rules (RuleMap, ParamRuleMap, dependent rules)
func (v *Validator) validateCommonRules(tags otherValidTags, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
for _, tag := range tags {
handled, err := v.checkDependentRulesWithStatus(tag, f, value, o, name, structName)
if err != nil {
return err
}
if err := v.applyRuleMaps(tag, value, f, name, structName, o, handled); err != nil {
return err
}
if value.Kind() == reflect.String {
if err := v.validateWithStringRulesMap(tag, value, f, name, structName, o); err != nil {
return err
}
if err := v.validateWithStringParamRulesMap(tag, value, f, name, structName, o); err != nil {
return err
}
}
}
return nil
}
// extractValuesFromCollection extracts string values from map or slice/array
func extractValuesFromCollection(field reflect.Value) ([]string, error) {
var values []string
switch field.Kind() {
case reflect.Map:
var sv stringValues
sv = field.MapKeys()
sort.Sort(sv)
for _, k := range sv {
mapValue := field.MapIndex(k)
if mapValue.Kind() == reflect.Interface || mapValue.Kind() == reflect.Pointer {
mapValue = mapValue.Elem()
}
if mapValue.Kind() != reflect.Struct {
values = append(values, ToString(mapValue.Interface()))
} else {
return nil, fmt.Errorf("validator: RequiredIf unsupported type %T", mapValue.Interface())
}
}
case reflect.Slice, reflect.Array:
for i := 0; i < field.Len(); i++ {
sliceValue := field.Index(i)
if sliceValue.Kind() == reflect.Interface || sliceValue.Kind() == reflect.Pointer {
sliceValue = sliceValue.Elem()
}
if sliceValue.Kind() != reflect.Struct {
values = append(values, ToString(sliceValue.Interface()))
} else {
return nil, fmt.Errorf("validator: RequiredIf unsupported type %T", sliceValue.Interface())
}
}
}
return values, nil
}
// checkRequiredIfCondition checks if the required condition is met and updates tag parameters
// checkRequiredIfCondition reports whether the field is required (invalid) and,
// when it is, the matched value that triggered the requirement. It must not
// mutate any cached tag — the matched value is returned to the caller so the
// "Value" message parameter can be built per call.
func checkRequiredIfCondition(v reflect.Value, values, params []string) (valid bool, matchedValue string, err error) {
for _, value := range values {
if InString(value, params) && Empty(v) {
return false, value, nil
}
}
return true, "", nil
}
// isCustomTypeRules validates using CustomTypeRuleMap
func (v *Validator) validateCustomTypeRules(tags otherValidTags, value reflect.Value, f *field, name, structName string, o reflect.Value) error {
for _, tag := range tags {
if validatefunc, ok := CustomTypeRuleMap.Get(tag.name); ok {
if result := validatefunc(value, o, tag); !result {
return v.formatsMessages(v.createFieldError(
name, structName, tag.name, tag.messageName,
parseValidatorMessageParameters(tag, o),
f.attribute, f.defaultAttribute,
ToString(value.Interface()), nil,
))
}
}
}
return nil
}
// isMapFields validates map structure and each element
func (v *Validator) validateMapFields(value reflect.Value, f *field, jsonNamespace, structNamespace []byte, depth int) error {
if value.Type().Key().Kind() != reflect.String {
return &UnsupportedTypeError{value.Type()}
}
sv := stringValues(value.MapKeys())
sort.Sort(sv)
for _, k := range sv {
var err error
item := value.MapIndex(k)
// Deref interface-valued map entries (e.g. map[string]any of
// structs). This checks item, not value: value is always the map, so
// the previous value.Kind()==Interface check never fired and such
// entries were silently skipped — inconsistent with validateSliceFields.
if item.Kind() == reflect.Interface {
item = item.Elem()
}
if item.Kind() == reflect.Struct || item.Kind() == reflect.Pointer {
key := []byte(k.String())
newJSONNamespace := appendNamespace(appendNamespace(jsonNamespace, f.nameBytes), key)
newstructNamespace := appendNamespace(appendNamespace(structNamespace, f.structNameBytes), key)
err = v.validateStruct(item.Interface(), newJSONNamespace, newstructNamespace, depth+1)
if err != nil {
return err
}
}
}
return nil
}
// isSliceFields validates slice/array structure and each element
func (v *Validator) validateSliceFields(value reflect.Value, f *field, jsonNamespace, structNamespace []byte, depth int) error {
for i := 0; i < value.Len(); i++ {
var err error
item := value.Index(i)
if item.Kind() == reflect.Interface {
item = item.Elem()
}
if item.Kind() == reflect.Struct || item.Kind() == reflect.Pointer {
index := []byte(strconv.Itoa(i))
newJSONNamespace := appendNamespace(appendNamespace(jsonNamespace, f.nameBytes), index)
newStructNamespace := appendNamespace(appendNamespace(structNamespace, f.structNameBytes), index)
err = v.validateStruct(value.Index(i).Interface(), newJSONNamespace, newStructNamespace, depth+1)
if err != nil {
return err
}
}
}
return nil
}
// IsBetween check The field under validation must have a size between the given min and max. Strings, numerics, arrays, and files are evaluated in the same fashion as the size rule.
func IsBetween(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isBetween(v, params)
}
// isDigitsBetween check The field under validation must have a length between the given min and max.
func isDigitsBetween(v reflect.Value, params []string) (bool, error) {
if len(params) != 2 {
return false, fmt.Errorf("validator: DigitsBetween params length must be 2")
}
switch v.Kind() {
case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
min, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for DigitsBetween rule on string field, min value: %w", err)
}
max, err := ToInt(params[1])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for DigitsBetween rule on string field, max value: %w", err)
}
var value string
switch v.Kind() {
case reflect.String:
value = v.String()
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
value = ToString(v.Int())
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
value = ToString(v.Uint())
}
if value == "" || !IsNumeric(value) {
return false, fmt.Errorf("validator: DigitsBetween value is not numeric")
}
return IsStringBetween(value, min, max), nil
}
return false, fmt.Errorf("validator: DigitsBetween unsupported type %T", v.Interface())
}
// IsDigitsBetween check The field under validation must have a length between the given min and max.
func IsDigitsBetween(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isDigitsBetween(v, params)
}
// isSize The field under validation must have a size matching the given value.
// For string data, value corresponds to the number of characters.
// For numeric data, value corresponds to a given integer value.
// For an array | map | slice, size corresponds to the count of the array | map | slice.
func isSize(v reflect.Value, param []string) (bool, error) {
valid := false
var err error
switch v.Kind() {
case reflect.String:
p, err := ToInt(param[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on string field, value: %w", err)
}
valid, err = compareString(v.String(), p, "==")
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on string field, value: %w", err)
}
case reflect.Slice, reflect.Map, reflect.Array:
p, err := ToInt(param[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on collection field, value: %w", err)
}
valid, err = compareInt64(int64(v.Len()), p, "==")
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on collection field, value: %w", err)
}
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p, err := ToInt(param[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
valid, err = compareInt64(v.Int(), p, "==")
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p, err := ToUint(param[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
valid, err = compareUint64(v.Uint(), p, "==")
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
case reflect.Float32, reflect.Float64:
p, err := ToFloat(param[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
valid, err = compareFloat64(v.Float(), p, "==")
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for Size rule on numeric field, value: %w", err)
}
default:
return false, fmt.Errorf("validator: Size unsupported type %T", v.Interface())
}
return valid, err
}
// IsSize The field under validation must have a size matching the given value.
// For string data, value corresponds to the number of characters.
// For numeric data, value corresponds to a given integer value.
// For an array | map | slice, size corresponds to the count of the array | map | slice.
func IsSize(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isSize(v, params)
}
// isMax is the validation function for validating if the current field's value is less than or equal to the param's value.
func isMax(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opLte, "Max")
}
// IsMax is the validation function for validating if the current field's value is less than or equal to the param's value.
func IsMax(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isMax(v, params)
}
// isMin is the validation function for validating if the current field's value is greater than or equal to the param's value.
func isMin(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opGte, "Min")
}
// IsMin is the validation function for validating if the current field's value is greater than or equal to the param's value.
func IsMin(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isMin(v, params)
}
// isGtParam is the validation function for validating if the current field's value is greater than the param's value.
func isGtParam(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opGt, "Gt")
}
// IsGtParam is the validation function for validating if the current field's value is greater than the param's value.
func IsGtParam(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isGtParam(v, params)
}
// isGteParam is the validation function for validating if the current field's value is greater than or equal to the param's value.
func isGteParam(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opGte, "Gte")
}
// IsGteParam is the validation function for validating if the current field's value is greater than or equal to the param's value.
func IsGteParam(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isGteParam(v, params)
}
// isLtParam is the validation function for validating if the current field's value is less than the param's value.
func isLtParam(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opLt, "Lt")
}
// IsLtParam is the validation function for validating if the current field's value is less than the param's value.
func IsLtParam(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isLtParam(v, params)
}
// isLteParam is the validation function for validating if the current field's value is less than or equal to the param's value.
func isLteParam(v reflect.Value, params []string) (bool, error) {
return compareValue(v, params, opLte, "Lte")
}
// IsLteParam is the validation function for validating if the current field's value is less than or equal to the param's value.
func IsLteParam(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isLteParam(v, params)
}
// isSame is the validation function for validating if the current field's value equal the param's value.
func isSame(v, anotherField reflect.Value) (bool, error) {
return compareFields(v, anotherField, opEq, "Same")
}
// IsSame is the validation function for validating if the current field's value is greater than or equal to the param's value.
func IsSame(i, a any) (bool, error) {
v := reflect.ValueOf(i)
anotherField := reflect.ValueOf(a)
return isSame(v, anotherField)
}
// isLt is the validation function for validating if the current field's value is less than the param's value.
func isLt(v, anotherField reflect.Value) (bool, error) {
return compareFields(v, anotherField, opLt, "Lt")
}
// IsLt is the validation function for validating if the current field's value is less than the param's value.
func IsLt(i, a any) (bool, error) {
v := reflect.ValueOf(i)
anotherField := reflect.ValueOf(a)
return isLt(v, anotherField)
}
// isLte is the validation function for validating if the current field's value is less than or equal to the param's value.
func isLte(v, anotherField reflect.Value) (bool, error) {
return compareFields(v, anotherField, opLte, "Lte")
}
// IsLte is the validation function for validating if the current field's value is less than or equal to the param's value.
func IsLte(i, a any) (bool, error) {
v := reflect.ValueOf(i)
anotherField := reflect.ValueOf(a)
return isLte(v, anotherField)
}
// isGt is the validation function for validating if the current field's value is greater than to the param's value.
func isGt(v, anotherField reflect.Value) (bool, error) {
return compareFields(v, anotherField, opGt, "Gt")
}
// IsGt is the validation function for validating if the current field's value is greater than to the param's value.
func IsGt(i, a any) (bool, error) {
v := reflect.ValueOf(i)
anotherField := reflect.ValueOf(a)
return isGt(v, anotherField)
}
// isGte is the validation function for validating if the current field's value is greater than or equal to the param's value.
func isGte(v, anotherField reflect.Value) (bool, error) {
return compareFields(v, anotherField, opGte, "Gte")
}
// IsGte is the validation function for validating if the current field's value is greater than to the param's value.
func IsGte(i, a any) (bool, error) {
v := reflect.ValueOf(i)
anotherField := reflect.ValueOf(a)
return isGte(v, anotherField)
}
// isDistinct is the validation function for validating an attribute is unique among other values.
func isDistinct(v reflect.Value) (bool, error) {
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr,
reflect.Float32, reflect.Float64:
return true, nil
case reflect.Slice, reflect.Array:
// Only keys matter for uniqueness; use a zero-size value type so each
// entry stores nothing instead of a full copy of the collection.
seen := reflect.MakeMapWithSize(reflect.MapOf(v.Type().Elem(), emptyStructType), v.Len())
for i := 0; i < v.Len(); i++ {
seen.SetMapIndex(v.Index(i), emptyStructValue)
}
return v.Len() == seen.Len(), nil
case reflect.Map:
seen := reflect.MakeMapWithSize(reflect.MapOf(v.Type().Elem(), emptyStructType), v.Len())
for _, k := range v.MapKeys() {
seen.SetMapIndex(v.MapIndex(k), emptyStructValue)
}
return v.Len() == seen.Len(), nil
}
return false, fmt.Errorf("validator: Distinct unsupported type %T", v.Interface())
}
// IsDistinct is the validation function for validating an attribute is unique among other values.
func IsDistinct(i any) bool {
v := reflect.ValueOf(i)
valid, _ := isDistinct(v)
return valid
}
// isMultipleOf is the validation function for validating if the current field's value is a multiple of the param's value.
func isMultipleOf(v reflect.Value, params []string) (bool, error) {
if len(params) == 0 {
return false, fmt.Errorf("validator: multipleOf rule requires at least one parameter")
}
// Check for decimal.Decimal type first
if d, ok := asDecimal(v); ok {
p, _, err := parseDecimalParams(params)
if err != nil {
return false, fmt.Errorf("validator: multipleOf decimal: %w", err)
}
if p.IsZero() {
return false, fmt.Errorf("validator: multipleOf cannot divide by zero")
}
return d.Mod(p).IsZero(), nil
}
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
p, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for multipleOf rule: %w", err)
}
if p == 0 {
return false, fmt.Errorf("validator: multipleOf cannot divide by zero")
}
return v.Int()%p == 0, nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
p, err := ToUint(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for multipleOf rule: %w", err)
}
if p == 0 {
return false, fmt.Errorf("validator: multipleOf cannot divide by zero")
}
return v.Uint()%p == 0, nil
case reflect.Float32, reflect.Float64:
p, err := ToFloat(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for multipleOf rule: %w", err)
}
if p == 0 {
return false, fmt.Errorf("validator: multipleOf cannot divide by zero")
}
remainder := v.Float() / p
return remainder == float64(int64(remainder)), nil
default:
return false, fmt.Errorf("validator: multipleOf rule is not supported for type %s", v.Kind())
}
}
// IsMultipleOf is the validation function for validating if a value is a multiple of another.
func IsMultipleOf(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isMultipleOf(v, params)
}
// isMaxDigits is the validation function for validating the maximum number of digits.
func isMaxDigits(v reflect.Value, params []string) (bool, error) {
if len(params) == 0 {
return false, fmt.Errorf("validator: maxDigits rule requires at least one parameter")
}
maxDigits, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for maxDigits rule: %w", err)
}
var numStr string
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
numStr = strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
numStr = strconv.FormatUint(v.Uint(), 10)
case reflect.Float32, reflect.Float64:
numStr = strconv.FormatFloat(v.Float(), 'f', -1, 64)
case reflect.String:
numStr = v.String()
default:
return false, fmt.Errorf("validator: maxDigits rule is not supported for type %s", v.Kind())
}
// Remove negative sign and decimal point for counting
numStr = strings.TrimPrefix(numStr, "-")
numStr = strings.ReplaceAll(numStr, ".", "")
return int64(len(numStr)) <= maxDigits, nil
}
// IsMaxDigits is the validation function for validating the maximum number of digits.
func IsMaxDigits(i any, params []string) (bool, error) {
v := reflect.ValueOf(i)
return isMaxDigits(v, params)
}
// isMinDigits is the validation function for validating the minimum number of digits.
func isMinDigits(v reflect.Value, params []string) (bool, error) {
if len(params) == 0 {
return false, fmt.Errorf("validator: minDigits rule requires at least one parameter")
}
minDigits, err := ToInt(params[0])
if err != nil {
return false, fmt.Errorf("validator: invalid parameter for minDigits rule: %w", err)
}
var numStr string
switch v.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
numStr = strconv.FormatInt(v.Int(), 10)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
numStr = strconv.FormatUint(v.Uint(), 10)
case reflect.Float32, reflect.Float64:
numStr = strconv.FormatFloat(v.Float(), 'f', -1, 64)
case reflect.String:
numStr = v.String()
default:
return false, fmt.Errorf("validator: minDigits rule is not supported for type %s", v.Kind())
}
// Remove negative sign and decimal point for counting
numStr = strings.TrimPrefix(numStr, "-")
numStr = strings.ReplaceAll(numStr, ".", "")