-
Notifications
You must be signed in to change notification settings - Fork 126
Expand file tree
/
Copy pathvalidation.go
More file actions
938 lines (817 loc) · 28.5 KB
/
Copy pathvalidation.go
File metadata and controls
938 lines (817 loc) · 28.5 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
package validate
import (
"fmt"
"reflect"
"strings"
"sync"
"github.com/gookit/validate/v2/internal/fieldval"
)
// some default value settings.
const (
fieldTag = "json"
filterTag = "filter"
labelTag = "label"
messageTag = "message"
validateTag = "validate"
filterError = "_filter"
validateError = "_validate"
// sniff Length, use for detect file mime type
sniffLen = 512
// 32 MB
defaultMaxMemory int64 = 32 << 20
// validator type
validatorTypeBuiltin int8 = 1
validatorTypeCustom int8 = 2
)
// Validation definition
type Validation struct {
// pool is the owning sync.Pool when this instance was obtained from an
// opt-in Factory (see factory.go). nil for the default New/Struct/Map path,
// so Release() is a no-op there. Set by Factory.* and cleared on Release().
pool *sync.Pool
// source input data
data DataFace
// sd is a reusable StructData carried by POOLED instances (Factory / Check) so
// a struct validation does not allocate a new StructData + fieldNames map on
// every call. nil on the default New/Struct/Map path. It is reset (source
// unbound, caches cleared) on reuse — see resetForReuse + StructData.fromStruct.
sd *StructData
// all validated fields list
// fields []string
// save filtered/validated safe data
safeData M
// filtered clean data
filteredData M
// save user custom set default values
defValues map[string]any
// Errors for validate
Errors Errors
// CacheKey for cache rules
// CacheKey string
// StopOnError If true: An error occurs, it will cease to continue to verify
StopOnError bool
// SkipOnEmpty Skip check on field not exist or value is empty
SkipOnEmpty bool
// UpdateSource Whether to update source field value, useful for struct validate
UpdateSource bool
// CheckDefault Whether to validate the default value set by the user
CheckDefault bool
// ErrShowValue Whether to append the failing value to the error message.
// opt-in, copied from gOpt. see GitHub issue #184.
ErrShowValue bool
// CachingRules switch. default is False
// CachingRules bool
// mark has error occurs
hasError bool
// mark is filtered
hasFiltered bool
// mark is validated
hasValidated bool
// validate rules for the validation
rules []*Rule
// validators for the validation. map-value: 1=builtin, 2=custom
validators map[string]int8
// validator func meta info
validatorMetas map[string]*funcMeta
// current scene name
scene string
// scenes config.
// {
// "create": {"field0", "field1"}
// "update": {"field0", "field2"}
// }
scenes SValues
// should check fields in current scene.
sceneFields map[string]uint8
// scene fields that carry a ".*" wildcard (eg "Tags.*.Id"); matched against the
// indexed rule names generated for slice elements (eg "Tags.0.Id"). (#283)
sceneWildcards map[string]uint8
// filtering rules for the validation
filterRules []*FilterRule
// filter func reflect.Value map
filterValues map[string]reflect.Value
// translator instance
trans *Translator
// optional fields, useful for sub-struct field in struct data. eg: "Parent"
//
// key is field name, value is field vale is: init=0 empty=1 not-empty=2.
optionals map[string]int8
// CheckErr(skipCollect) 模式状态。skipCollect=true 时跳过 safeData/filteredData
// 收集,改用 scKey/scVal 1 槽缓存对"同字段连续取值"做装箱去重(镜像 safeData 的
// 去重职责)。详见 docs/perf/checkerr-impl-plan.md。
skipCollect bool
// needCollect 由 ValidateR/Check 置真以强制收集 safeData/filteredData,压过
// struct 源在 Validate() 的自动 skipCollect 快路径(它们要对外暴露 safeData)。
needCollect bool
scKey string
scVal any
// scRV 缓存 struct 源字段的已提交 reflect.Value(值类型, 3 字, box-free)。
// scIsRV=true 时用 scRV 做同字段去重(免重读源、不装箱), 且因是值类型不是
// *FieldValue 指针, 不会导致 getFieldCarrier 现造的载体逃逸到堆。
scRV reflect.Value
scIsRV bool
}
// NewEmpty new validation instance, but not with data.
func NewEmpty(scene ...string) *Validation {
return NewValidation(nil, scene...)
}
// NewValidation new validation instance
func NewValidation(data DataFace, scene ...string) *Validation {
return newValidation(data).SetScene(scene...)
}
/*************************************************************
* lazy map allocation guards (perf Step 2)
*
* Each per-instance map in newEmpty() is allocated on FIRST WRITE only. Writing
* to a nil map panics, so every write site must call its ensure*() first; reads
* (range/len/index-get/comma-ok) are nil-safe and need no guard.
*************************************************************/
func (v *Validation) ensureErrors() {
if v.Errors == nil {
v.Errors = make(Errors)
}
}
func (v *Validation) ensureSafeData() {
if v.safeData == nil {
v.safeData = make(map[string]any)
}
}
func (v *Validation) ensureFilteredData() {
if v.filteredData == nil {
v.filteredData = make(map[string]any)
}
}
// commitValue records a field's validated value carrier: into the skipCollect
// 1-slot cache (CheckErr fast path) or into safeData (normal collect path,
// materializes via Src() — §9 safeData 墙).
//
// 逃逸约束(R4 关键): 绝不把载体指针 fv 存进 *Validation 这种逃逸结构,否则
// escape 分析会把 getFieldCarrier 现造的所有载体标记为 escapes-to-heap,连带
// struct 热路径载体逃逸(实测 +N allocs)。scRV 缓存的是 reflect.Value 值类型
// (非 *FieldValue 指针), 故 box-free 且不致载体逃逸。因此:
// - struct 源 skipCollect: 缓存 fv.RV()(已提交值的 rv, box-free), scIsRV=true。
// 同字段后续规则直接复用此 rv, 免重读源、不装箱, 且即为已提交值(闭合非指针写回边界)。
// - map/form 源 skipCollect: 值本就是 any, 记 scVal=fv.Src()(无额外装箱)。
// - 非 skipCollect: safeData 收集恒装箱(§9 的墙), 用 Src() 物化。
func (v *Validation) commitValue(field string, fv *fieldval.FieldValue) {
if v.skipCollect {
v.scKey = field
if v.data != nil && v.data.Type() == sourceStruct {
// 缓存字段值的 reflect.Value(值类型, 3 字, 不装箱、不致载体逃逸)。
// fv.RV() 对 NewRV 载体=源字段 rv; 对默认/过滤重建的 New 载体=新值 rv。
// 同字段后续规则直接复用此 rv, 免重读源、box-free, 且即为已提交值(闭合非指针写回边界)。
v.scRV, v.scIsRV = fv.RV(), true
v.scVal = nil
} else {
// map/form: 值本就是 any, 记下以对同字段连续读去重(语义同改造前)。
v.scVal, v.scIsRV = fv.Src(), false
v.scRV = reflect.Value{}
}
return
}
v.ensureSafeData()
v.safeData[field] = fv.Src()
}
func (v *Validation) ensureOptionals() {
if v.optionals == nil {
v.optionals = make(map[string]int8)
}
}
func (v *Validation) ensureValidatorMaps() {
if v.validators == nil {
v.validators = make(map[string]int8)
}
if v.validatorMetas == nil {
v.validatorMetas = make(map[string]*funcMeta)
}
}
/*************************************************************
* validation settings
*************************************************************/
// ResetResult reset the validate result.
func (v *Validation) ResetResult() {
// Step 2: result maps reset to nil (lazily re-allocated on first write), so a
// Reset()'d instance keeps the no-alloc property on the next clean validation.
v.Errors = nil
v.hasError = false
v.hasFiltered = false
v.hasValidated = false
// result data
v.safeData = nil
v.filteredData = nil
}
// Reset the Validation instance.
//
// Will resets:
// - validate result
// - validate rules
// - validate filterRules
// - custom validators TODO
func (v *Validation) Reset() {
v.ResetResult()
// v.validators = make(map[string]int8)
v.resetRules()
}
func (v *Validation) resetRules() {
// reset rules
v.rules = v.rules[:0]
v.optionals = nil // lazily re-allocated on first write (ensureOptionals)
v.filterRules = v.filterRules[:0]
}
// resetForReuse fully resets ALL per-validation state back to the newEmpty()
// initial values, so a pooled instance can be safely reused for a different
// data source/type without any cross-validation data leak.
//
// This is intentionally a separate method from Reset()/ResetResult() (which only
// clear the result + rules and are part of the public, default-path API). It is
// only used by the opt-in Factory (factory.go) and Release(). Every field set in
// newEmpty()/NewValidation()/Create() that can be mutated during a validation is
// restored here. The pool field itself is NOT touched (Release manages it).
func (v *Validation) resetForReuse() {
// --- source input ---
v.data = nil
// pooled StructData: unbind source + clear field caches but KEEP the
// allocation for reuse. Prevents a pooled instance from pinning the last
// validated struct while it sits idle in the pool.
if v.sd != nil {
v.sd.reset()
}
// --- result data + flags (mirrors ResetResult, but clears maps in place to
// reuse the already-allocated buckets — this is the whole point of pooling) ---
clear(v.Errors)
v.hasError = false
v.hasFiltered = false
v.hasValidated = false
clear(v.safeData)
clear(v.filteredData)
// user custom default values (lazily allocated, see SetDefValue)
clear(v.defValues)
// --- config flags: restore to global defaults (newEmpty uses gOpt) ---
// NOTE: Struct() sets UpdateSource=true after Create; CheckDefault may be
// toggled by callers. All must go back to the New-time initial values.
v.StopOnError = gOpt.StopOnError
v.SkipOnEmpty = gOpt.SkipOnEmpty
v.ErrShowValue = gOpt.ErrShowValue
v.UpdateSource = false
v.CheckDefault = false
// --- rules / filter rules / optionals (mirrors resetRules; keep cap) ---
v.rules = v.rules[:0]
v.filterRules = v.filterRules[:0]
clear(v.optionals)
// --- validators: drop per-type custom validators + lazily-bound ctx metas.
// newEmpty() starts with empty maps; ctx validators rebind lazily to this
// same v on next lookup (validatorMeta), so clearing is correct & required
// (a struct's own FuncValue / AddValidator entries are type-specific). ---
clear(v.validators)
clear(v.validatorMetas)
// instance-level custom filter funcs (lazily allocated, see AddFilter)
clear(v.filterValues)
// --- scene state ---
v.scene = ""
v.scenes = nil
v.sceneFields = nil
v.sceneWildcards = nil
// --- translator: reset custom messages/labels/field-map back to empty.
// Clear in place (matches Translator.Reset semantics: messages=nil custom
// only, label/field maps emptied) to avoid 2 map allocs per reuse. ---
clear(v.trans.messages)
v.trans.messages = nil
clear(v.trans.labelMap)
clear(v.trans.fieldMap)
// --- CheckErr(skipCollect) 状态:必须清,否则 CheckErr 用过的池实例被 Check
// 复用时会残留 skipCollect=true 导致 Check 收不到 safeData。 ---
v.skipCollect = false
v.needCollect = false
v.scKey = ""
v.scVal = nil
v.scRV = reflect.Value{}
v.scIsRV = false
}
// TODO Config(opt *Options) *Validation
// WithSelf config the Validation instance. TODO rename to WithConfig
func (v *Validation) WithSelf(fn func(v *Validation)) *Validation {
fn(v)
return v
}
// WithTrans with a custom translator
func (v *Validation) WithTrans(trans *Translator) *Validation {
v.trans = trans
return v
}
// WithScenarios is alias of the WithScenes()
func (v *Validation) WithScenarios(scenes SValues) *Validation {
return v.WithScenes(scenes)
}
// WithScenes set scene config.
//
// Usage:
//
// v.WithScenes(SValues{
// "create": []string{"name", "email"},
// "update": []string{"name"},
// })
// ok := v.AtScene("create").Validate()
func (v *Validation) WithScenes(scenes map[string][]string) *Validation {
v.scenes = scenes
return v
}
// AtScene setting current validate scene.
func (v *Validation) AtScene(scene string) *Validation {
v.scene = scene
return v
}
// InScene alias of the AtScene()
func (v *Validation) InScene(scene string) *Validation {
return v.AtScene(scene)
}
// SetScene alias of the AtScene()
func (v *Validation) SetScene(scene ...string) *Validation {
if len(scene) > 0 {
v.AtScene(scene[0])
}
return v
}
/*************************************************************
* add validators for validation
*************************************************************/
// AddValidators to the Validation instance.
func (v *Validation) AddValidators(m map[string]any) *Validation {
for name, checkFunc := range m {
v.AddValidator(name, checkFunc)
}
return v
}
// AddValidator to the Validation instance. checkFunc must return a bool.
//
// Usage:
//
// v.AddValidator("myFunc", func(data validate.DataFace, val any) bool {
// // do validate val ...
// return true
// })
func (v *Validation) AddValidator(name string, checkFunc any) *Validation {
fv := checkValidatorFunc(name, checkFunc)
v.ensureValidatorMaps() // lazy
v.validators[name] = validatorTypeCustom
// v.validatorValues[name] = fv
v.validatorMetas[name] = newFuncMeta(name, false, fv)
return v
}
// ValidatorMeta get by name. get validator from global or validation instance.
func (v *Validation) validatorMeta(name string) *funcMeta {
// current validation
if fm, ok := v.validatorMetas[name]; ok {
return fm
}
// from global validators
if fm, ok := validatorMetas[name]; ok {
return fm
}
// lazy-build a build-in context validator on first lookup (perf P5b).
// binds the real v so both the switch-direct path (required-family, uses
// only fm.Type()) and the reflect Call path (eqField/file..., needs the
// receiver) behave identically to the previous eager construction.
if builder, ok := ctxValidatorBuilders[name]; ok {
fm := newFuncMeta(name, true, builder(v))
v.ensureValidatorMaps() // lazy
v.validators[name] = validatorTypeBuiltin
v.validatorMetas[name] = fm
return fm
}
// if v.data is StructData instance.
if v.data.Type() == sourceStruct {
fv, ok := v.data.(*StructData).FuncValue(name)
if ok {
fm := newFuncMeta(name, false, fv)
// storage it.
v.ensureValidatorMaps() // lazy
v.validators[name] = validatorTypeCustom
v.validatorMetas[name] = fm
return fm
}
}
return nil
}
// HasValidator check
func (v *Validation) HasValidator(name string) bool {
name = ValidatorName(name)
// current validation
if _, ok := v.validatorMetas[name]; ok {
return true
}
// build-in context validators are always available (bound lazily).
if _, ok := ctxValidatorBuilders[name]; ok {
return true
}
// global validators
_, ok := validatorMetas[name]
return ok
}
// Validators get all validator names
func (v *Validation) Validators(withGlobal bool) map[string]int8 {
mp := make(map[string]int8, len(v.validators)+len(ctxValidatorBuilders))
if withGlobal {
for name, typ := range validators {
mp[name] = typ
}
}
// include the build-in context validators (always available, bound
// lazily so they may not yet be present in v.validators after P5b).
for name := range ctxValidatorBuilders {
mp[name] = validatorTypeBuiltin
}
// instance validators last: already-built ctx + custom override above.
for name, typ := range v.validators {
mp[name] = typ
}
return mp
}
/*************************************************************
* Do filtering/sanitize
*************************************************************/
// Sanitize data by filter rules
func (v *Validation) Sanitize() bool { return v.Filtering() }
// Filtering data by filter rules
func (v *Validation) Filtering() bool {
if v.hasFiltered {
return v.IsSuccess()
}
// apply rule to validate data.
for _, rule := range v.filterRules {
if err := rule.Apply(v); err != nil { // has error
v.AddError(filterError, filterError, rule.fields[0]+": "+err.Error())
break
}
}
v.hasFiltered = true
return v.IsSuccess()
}
/*************************************************************
* errors messages
*************************************************************/
// WithTranslates settings. you can be custom field translates.
//
// Usage:
//
// v.WithTranslates(map[string]string{
// "name": "Username",
// "pwd": "Password",
// })
func (v *Validation) WithTranslates(m map[string]string) *Validation {
v.trans.AddLabelMap(m)
return v
}
// AddTranslates settings data. like WithTranslates()
func (v *Validation) AddTranslates(m map[string]string) {
v.trans.AddLabelMap(m)
}
// WithMessages settings. you can custom validator error messages.
//
// Usage:
//
// // key is "validator" or "field.validator"
// v.WithMessages(map[string]string{
// "require": "oh! {field} is required",
// "range": "oh! {field} must be in the range %d - %d",
// })
func (v *Validation) WithMessages(m map[string]string) *Validation {
v.trans.AddMessages(m)
return v
}
// AddMessages settings data. like WithMessages()
func (v *Validation) AddMessages(m map[string]string) {
v.trans.AddMessages(m)
}
// WithError add error of the validation
func (v *Validation) WithError(err error) *Validation {
if err != nil {
v.AddError(validateError, validateError, err.Error())
}
return v
}
// AddError message for a field
func (v *Validation) AddError(field, validator, msg string) {
if !v.hasError {
v.hasError = true
}
v.ensureErrors() // lazy: only the error path allocates Errors
field = v.trans.FieldName(field)
v.Errors.Add(field, validator, msg)
}
// AddErrorf add a formatted error message
func (v *Validation) AddErrorf(field, msgFormat string, args ...any) {
v.AddError(field, validateError, fmt.Sprintf(msgFormat, args...))
}
// Trans get translator
func (v *Validation) Trans() *Translator {
// if v.trans == nil {
// v.trans = StdTranslator
// }
return v.trans
}
func (v *Validation) convArgTypeError(field, name string, argKind, wantKind reflect.Kind, argIdx int) {
v.AddErrorf(field, "cannot convert %s to arg#%d(%s), validator '%s'", argKind, argIdx, wantKind, name)
}
/*************************************************************
* getter methods
*************************************************************/
// Raw value get by key
func (v *Validation) Raw(key string) (any, bool) {
if v.data == nil { // check input data
return nil, false
}
return v.data.Get(key)
}
// RawVal value get by key
func (v *Validation) RawVal(key string) any {
if v.data == nil { // check input data
return nil
}
val, _ := v.data.Get(key)
return val
}
// try to get value by key.
//
// **NOTE:**
//
// If v.data is StructData, will return zero value check. Other dataSource will always return `zero=False`.
func (v *Validation) tryGet(key string) (val any, exist, zero bool) {
if v.data == nil {
return
}
// CheckErr(skipCollect): safeData/filteredData 不收集,改用 1 槽对同字段连续读
// 去重;其它字段落源(源已写回默认/过滤值,故读到已解析值,见计划 §4)。
//
// struct 源: commitValue 缓存已提交字段的 scRV(box-free), 命中即装箱返回(any
// 消费者如跨字段规则本就需要 any, 此装箱可接受, 非 0-alloc 热路径; 且 scRV 即
// 已提交值, 比重读源更稳)。map/form 源: updateValue 不写源, scVal 缓存是过滤/
// 默认值的唯一来源, 命中即返回。两路都是"已提交值"载体, 与改造前语义一致。
if v.skipCollect {
if v.scKey == key {
if v.scIsRV {
return v.scRV.Interface(), true, false
}
if v.scVal != nil {
return v.scVal, true, false
}
}
return v.data.TryGet(key)
}
// find from filtered data.
if val1, ok := v.filteredData[key]; ok {
return val1, true, false
}
// find from validated data. (such as has default value)
if val2, ok := v.safeData[key]; ok {
return val2, true, false
}
// TODO add cache data v.caches[key]
// get from source data
return v.data.TryGet(key)
}
// Get value by key.
func (v *Validation) Get(key string) (val any, exist bool) {
val, exist, _ = v.tryGet(key)
return
}
// GetWithDefault get field value by key.
//
// On not found, if it has default value, will return default-value.
func (v *Validation) GetWithDefault(key string) (val any, exist, isDefault bool) {
var zero bool
val, exist, zero = v.tryGet(key)
if exist && !zero {
return
}
// try read custom default value
defVal, isDefault := v.defValues[key]
if isDefault {
val = defVal
}
return
}
// fieldResolve is the by-VALUE result of getFieldCarrier: it carries everything
// applyField needs to build the carrier ITSELF (inline, on its own stack frame),
// so the *fieldval.FieldValue never escapes through a function return — the R4
// escape trap that turned every carrier into a heap alloc (实测 CheckErrValid
// 3→6). useRV picks NewRV(rv) (struct, box-free) vs New(val) (any) at the call
// site; exist/isDefault keep GetWithDefault semantics byte-for-byte.
type fieldResolve struct {
rv reflect.Value // struct 源的字段值(useRV=true 时有效)
val any // map/form/dedup/filtered/safeData/默认值(useRV=false 时有效)
useRV bool // true → applyField 用 NewRV(rv) 懒构造; false → New(val)
exist bool
isDefault bool
}
// getFieldCarrier resolves a field to a fieldResolve descriptor with byte-for-byte
// identical (exist, isDefault) semantics to GetWithDefault, but for STRUCT sources
// it returns the raw reflect.Value (useRV=true) so the caller can build the carrier
// via NewRV — keeping the boxed value lazy so a pass-through (struct) validation
// never calls Interface() (痛点 R4 端到端去装箱).
//
// Branch equivalence to GetWithDefault→tryGet (must stay lock-step):
// - v.data == nil → exist=false; only defValues can flip isDefault.
// - skipCollect && scKey==field → (struct: 源重读 tryGetRV; map/form: scVal dedup).
// - filtered / safeData hit → any (useRV=false), exist=true, zero=false.
// - struct source → tryGetRV(field) (exist, zero); useRV=true (lazy).
// - map/form source → data.TryGet(field) (any) → useRV=false.
// - then: if !(exist && !zero) and defValues[field] exists → val=defVal, isDefault=true.
func (v *Validation) getFieldCarrier(field string) fieldResolve {
var r fieldResolve
var zero bool
if v.data == nil {
// mirrors tryGet's nil return (val=nil, exist=false, zero=false).
r.exist, zero = false, false
} else if v.skipCollect {
// skipCollect dedup (mirrors tryGet), 命中同字段三路:
// - struct 源: 复用缓存的已提交 rv(scIsRV), box-free、免重读源, useRV=true
// 让 applyField 经 NewRV 懒构造载体(把 Age 的 min/max 两次重读降为零次);
// scRV 即已提交值, 比重读源更稳(闭合非指针写回边界)。
// - map/form 源(或已物化的 scVal): updateValue 不写源, scVal 是唯一来源 → 命中即包装。
// - 未命中: 经 resolveSource 落源(struct: tryGetRV; map/form: TryGet)。
if v.scKey == field {
if v.scIsRV {
r.rv, r.useRV, r.exist, zero = v.scRV, true, true, false
} else if v.scVal != nil {
r.val, r.exist, zero = v.scVal, true, false
} else {
r.rv, r.val, r.useRV, r.exist, zero = v.resolveSource(field)
}
} else {
r.rv, r.val, r.useRV, r.exist, zero = v.resolveSource(field)
}
} else {
// normal collect path: filtered → safeData → source (mirrors tryGet).
if val1, ok := v.filteredData[field]; ok {
r.val, r.exist, zero = val1, true, false
} else if val2, ok := v.safeData[field]; ok {
r.val, r.exist, zero = val2, true, false
} else {
r.rv, r.val, r.useRV, r.exist, zero = v.resolveSource(field)
}
}
// GetWithDefault: if value exists and is non-zero, no default substitution.
if r.exist && !zero {
return r
}
// try read custom default value (replaces the value with the default; any).
if defVal, ok := v.defValues[field]; ok {
r.val, r.rv, r.useRV, r.isDefault = defVal, reflect.Value{}, false, true
return r
}
// no default: keep the resolved (possibly zero/not-exist) descriptor as-is.
return r
}
// resolveSource reads the field straight from the data source: struct sources
// return the reflect.Value (useRV=true, lazy/box-free); other sources box via
// TryGet (useRV=false). Mirrors the v.data.TryGet(field) tail of tryGet.
func (v *Validation) resolveSource(field string) (rv reflect.Value, val any, useRV, exist, zero bool) {
if sd, ok := v.data.(*StructData); ok {
fv, ex, zr := sd.tryGetRV(field)
if !ex {
// not-exist: TryGet would return (nil, false, false). val=nil so the
// caller's New(field, nil) matches the boxed not-exist path.
return reflect.Value{}, nil, false, false, false
}
return fv, nil, true, true, zr
}
// map/form: value is already any.
val, exist, zero = v.data.TryGet(field)
return reflect.Value{}, val, false, exist, zero
}
// Set value by key
func (v *Validation) Set(field string, val any) error {
// check input data
if v.data == nil {
return ErrEmptyData
}
_, err := v.data.Set(field, val)
return err
}
// only update set value by key for struct
func (v *Validation) updateValue(field string, val any) (any, error) {
// data source is struct
if v.data.Type() == sourceStruct {
return v.data.Set(strings.TrimSuffix(field, ".*"), val)
}
// TODO dont update value for Form and Map data source
return val, nil
}
// SetDefValue set a default value of given field
func (v *Validation) SetDefValue(field string, val any) {
if v.defValues == nil {
v.defValues = make(map[string]any)
}
v.defValues[field] = val
}
// GetDefValue get default value of the field
func (v *Validation) GetDefValue(field string) (any, bool) {
defVal, ok := v.defValues[field]
return defVal, ok
}
// SceneFields field names get
func (v *Validation) SceneFields() []string {
return v.scenes[v.scene]
}
// scene field name map build. also (re)builds v.sceneWildcards for ".*" entries.
func (v *Validation) sceneFieldMap() (m map[string]uint8) {
v.sceneWildcards = nil
if v.scene == "" {
return
}
if fields, ok := v.scenes[v.scene]; ok {
// keep the map non-nil even when every field is skipped: a defined scene
// that yields no fields (eg: scenes{"None": {""}}) must be distinguishable
// from "no scene set" (nil map) in isNotNeedToCheck().
m = make(map[string]uint8, len(fields))
for _, field := range fields {
// skip empty scene field. otherwise the "" key would match the empty
// prefix fields[0:0] for every field and force-check everything (#314).
if field == "" {
continue
}
// ".*" wildcard entry (eg "Tags.*.Id"): kept apart so isNotNeedToCheck
// can match it against indexed slice-element rule names like "Tags.0.Id"
// (the scene field list otherwise matches by exact string only). (#283)
if strings.Contains(field, ".*") {
if v.sceneWildcards == nil {
v.sceneWildcards = make(map[string]uint8)
}
v.sceneWildcards[field] = 1
continue
}
m[field] = 1
}
}
return
}
// Scene name get for current validation
func (v *Validation) Scene() string { return v.scene }
// IsOK for the validating
func (v *Validation) IsOK() bool { return !v.hasError }
// IsFail for the validating
func (v *Validation) IsFail() bool { return v.hasError }
// IsSuccess for the validating
func (v *Validation) IsSuccess() bool { return !v.hasError }
/*************************************************************
* helper methods
*************************************************************/
// on stop on error
func (v *Validation) shouldStop() bool {
return v.hasError && v.StopOnError
}
// check current field is in optional parent field.
//
// return: true - optional parent field value is empty.
func (v *Validation) isInOptional(field string) bool {
for name, flag := range v.optionals {
// check like: field="Parent.Child" name="Parent"
if strings.HasPrefix(field, name+".") {
if flag != 0 {
return flag == 1 // 1=empty
}
pVal, exist, zero := v.tryGet(name)
if !exist || zero {
v.optionals[name] = 1
return true // not check field.
}
if IsEmpty(pVal) {
v.optionals[name] = 1
return true // not check field.
}
v.optionals[name] = 2
return false
}
}
return false
}
func (v *Validation) isNotNeedToCheck(field string) bool {
// nil sceneFields AND no wildcard entries: no scene set (or scene not defined)
// -> check all fields.
if v.sceneFields == nil && len(v.sceneWildcards) == 0 {
return false
}
// exact / ancestor-prefix match against the plain scene field list.
// start at i=1: fields[0:0] is the empty prefix and never a valid scene key.
if len(v.sceneFields) > 0 {
fields := strings.Split(field, ".")
for i := 1; i < len(fields); i++ {
if _, ok := v.sceneFields[strings.Join(fields[0:i], ".")]; ok {
return false
}
}
if _, ok := v.sceneFields[field]; ok {
return false
}
}
// wildcard match: normalize numeric index segments to "*" and look up.
// eg field "Tags.0.Id" -> "Tags.*.Id" matches scene entry "Tags.*.Id". (#283)
if len(v.sceneWildcards) > 0 {
if pat, hasIdx := indexPathToWildcard(field); hasIdx {
if _, ok := v.sceneWildcards[pat]; ok {
return false
}
}
}
return true
}