-
Notifications
You must be signed in to change notification settings - Fork 116
/
issues_test.go
1759 lines (1492 loc) · 43.2 KB
/
issues_test.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
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 validate_test
import (
"encoding/json"
"fmt"
"strings"
"testing"
"time"
"github.com/gookit/goutil"
"github.com/gookit/goutil/maputil"
"github.com/gookit/goutil/timex"
"github.com/gookit/validate/locales/zhcn"
"github.com/gookit/goutil/dump"
"github.com/gookit/goutil/jsonutil"
"github.com/gookit/goutil/testutil/assert"
"github.com/gookit/validate"
)
func TestIssue_2(t *testing.T) {
type Fl struct {
A float64 `validate:"float"`
}
fl := Fl{123}
v := validate.Struct(fl)
assert.True(t, v.Validate())
assert.Equal(t, float64(123), v.SafeVal("A"))
val, ok := v.Raw("A")
assert.True(t, ok)
assert.Equal(t, float64(123), val)
// Set value
err := v.Set("A", float64(234))
assert.Error(t, err)
// field not exist
err = v.Set("B", 234)
assert.Error(t, err)
// NOTICE: Must use ptr for set value
v = validate.Struct(&fl)
err = v.Set("A", float64(234))
assert.Nil(t, err)
// check new value
val, ok = v.Raw("A")
assert.True(t, ok)
assert.Equal(t, float64(234), val)
// int will convert to float
err = v.Set("A", 23)
assert.Nil(t, err)
// type is error
err = v.Set("A", "abc")
assert.Error(t, err)
assert.ErrMsg(t, err, `strconv.ParseFloat: parsing "abc": invalid syntax`)
}
// https://github.com/gookit/validate/issues/19
func TestIssues_19(t *testing.T) {
is := assert.New(t)
// use tag name: country_code
type smsReq struct {
CountryCode string `json:"country_code" validate:"required" filter:"trim|lower"`
Phone string `json:"phone" validate:"required" filter:"trim"`
Type string `json:"type" validate:"required|in:register,forget_password,set_pay_password,reset_pay_password,reset_password" filter:"trim"`
}
req := &smsReq{
" ABcd ", "13677778888 ", "register",
}
v := validate.New(req)
is.True(v.Validate())
sd := v.SafeData()
is.Equal("abcd", sd["CountryCode"])
is.Equal("13677778888", sd["Phone"])
// Notice: since 1.2, filtered value will update to struct
// err := v.BindSafeData(req)
// is.NoError(err)
is.Equal("abcd", req.CountryCode)
is.Equal("13677778888", req.Phone)
// use tag name: countrycode
type smsReq1 struct {
// CountryCode string `json:"countryCode" validate:"required" filter:"trim|lower"`
CountryCode string `json:"countrycode" validate:"required" filter:"trim|lower"`
Phone string `json:"phone" validate:"required" filter:"trim"`
Type string `json:"type" validate:"required|in:register,forget_password,set_pay_password,reset_pay_password,reset_password" filter:"trim"`
}
req1 := &smsReq1{
" ABcd ", "13677778888 ", "register",
}
v = validate.New(req1)
is.True(v.Validate())
sd = v.SafeData()
is.Equal("abcd", sd["CountryCode"])
is.Equal("abcd", req1.CountryCode)
is.Equal("13677778888", req1.Phone)
}
// https://github.com/gookit/validate/issues/20
func TestIssues_20(t *testing.T) {
is := assert.New(t)
type setProfileReq struct {
Nickname string `json:"nickname" validate:"string" filter:"trim"`
Avatar string `json:"avatar" validate:"required|url" filter:"trim"`
}
req := &setProfileReq{"123nickname111", "123"}
v := validate.New(req)
is.True(v.Validate())
type setProfileReq1 struct {
Nickname string `json:"nickname" validate:"string" filter:"trim"`
Avatar string `json:"avatar" validate:"required|fullUrl" filter:"trim"`
}
req1 := &setProfileReq1{"123nickname111", "123"}
validate.Config(func(opt *validate.GlobalOption) {
opt.FieldTag = ""
})
v = validate.New(req1)
is.False(v.Validate())
is.Len(v.Errors, 1)
is.Equal("Avatar must be a valid full URL address", v.Errors.One())
validate.ResetOption()
v = validate.New(req1)
is.False(v.Validate())
is.Len(v.Errors, 1)
is.Equal("avatar must be a valid full URL address", v.Errors.One())
}
// https://github.com/gookit/validate/issues/22
func TestIssues_22(t *testing.T) {
type userInfo0 struct {
Nickname string `validate:"minLen:6" message:"OO! nickname min len is 6"`
Avatar string `validate:"maxLen:6" message:"OO! avatar max len is %d"`
}
is := assert.New(t)
u0 := &userInfo0{
Nickname: "tom",
Avatar: "https://github.com/gookit/validate/issues/22",
}
v := validate.Struct(u0)
is.False(v.Validate())
is.Equal("OO! nickname min len is 6", v.Errors.FieldOne("Nickname"))
u0 = &userInfo0{
Nickname: "inhere",
Avatar: "some url",
}
v = validate.Struct(u0)
is.False(v.Validate())
is.Equal("OO! avatar max len is 6", v.Errors.FieldOne("Avatar"))
// multi messages
type userInfo1 struct {
Nickname string `validate:"required|min_len:6" message:"required:OO! nickname cannot be empty!|min_len:OO! nickname min len is %d"`
}
u1 := &userInfo1{Nickname: ""}
v = validate.Struct(u1)
is.False(v.Validate())
is.Equal("OO! nickname cannot be empty!", v.Errors.FieldOne("Nickname"))
u1 = &userInfo1{Nickname: "tom"}
v = validate.Struct(u1)
is.False(v.Validate())
is.Equal("OO! nickname min len is 6", v.Errors.FieldOne("Nickname"))
}
// https://github.com/gookit/validate/issues/30
func TestIssues_30(t *testing.T) {
v := validate.JSON(`{
"cost_type": 10
}`)
v.StringRule("cost_type", "str_num")
assert.True(t, v.Validate())
assert.Len(t, v.Errors, 0)
}
// https://github.com/gookit/validate/issues/34
func TestIssues_34(t *testing.T) {
type STATUS int32
var s1 STATUS = 1
// use custom validator
v := validate.New(validate.M{
"age": s1,
})
v.AddValidator("checkAge", func(val any, ints ...int) bool {
return validate.Enum(int32(val.(STATUS)), ints)
})
v.StringRule("age", "required|checkAge:1,2,3,4")
assert.True(t, v.Validate())
v = validate.New(validate.M{
"age": s1,
})
v.StringRules(validate.MS{
"age": "required|in:1,2,3,4",
})
assert.NotContains(t, []int{1, 2, 3, 4}, s1)
assert.True(t, v.Validate())
// dump.Println(validate.Enum(s1, []int{1, 2, 3, 4}), validate.Enum(int32(s1), []int{1, 2, 3, 4}))
// dump.Println(v.Errors)
type someMode string
var m1 someMode = "abc"
v = validate.New(validate.M{
"mode": m1,
})
v.StringRules(validate.MS{
"mode": "required|in:abc,def",
})
assert.True(t, v.Validate())
}
type issues36Form struct {
Name string `form:"username" json:"name" validate:"required|minLen:7"`
Email string `form:"email" json:"email" validate:"email"`
Age int `form:"age" validate:"required|int|min:18|max:150" json:"age"`
}
func (f issues36Form) Messages() map[string]string {
return validate.MS{
"required": "{field}不能为空",
"Name.minLen": "用户名最少7位",
"Name.required": "用户名不能为空",
"Email.email": "邮箱格式不正确",
"Age.min": "年龄最少18岁",
"Age.max": "年龄最大150岁",
}
}
func (f issues36Form) Translates() map[string]string {
return validate.MS{
"Name": "用户名",
"Email": "邮箱",
"Age": "年龄",
}
}
// https://github.com/gookit/validate/issues/36
func TestIssues36(t *testing.T) {
f := issues36Form{Age: 10, Name: "i am tom", Email: "[email protected]"}
v := validate.Struct(&f)
ok := v.Validate()
assert.False(t, ok)
assert.Equal(t, v.Errors.One(), "年龄最少18岁")
assert.Contains(t, v.Errors.String(), "年龄最少18岁")
}
// https://github.com/gookit/validate/issues/60
func TestIssues_60(t *testing.T) {
is := assert.New(t)
m := map[string]any{
"title": "1",
}
v := validate.Map(m)
v.StringRule("title", "in:2,3")
v.AddMessages(map[string]string{
"in": "自定义错误",
})
is.False(v.Validate())
is.Equal("自定义错误", v.Errors.One())
}
// https://github.com/gookit/validate/issues/64
// see validate.Enum()
func TestPtrFieldValidation(t *testing.T) {
type Foo struct {
Name *string `validate:"in:henry,jim"`
}
name := "henry"
v := validate.New(&Foo{Name: &name})
assert.True(t, v.Validate())
name = "fish"
valid := validate.New(&Foo{Name: &name})
assert.False(t, valid.Validate())
}
type Pet struct {
Breed string `json:"breed" validate:"min_len:3"`
Color string `json:"color" validate:"in:orange,black,brown"`
}
type Human struct {
Age int `json:"age" validate:"gt:13"`
Name string `json:"name" validate:"min_len:3"`
}
type Settings struct {
*Pet `json:",omitempty"`
*Human `json:",omitempty"`
}
type Entity struct {
ID string `json:"id" validate:"uuid4"`
Kind string `json:"kind" validate:"in:pet,human"`
Settings Settings `json:"settings"`
}
func (Entity) ConfigValidation(v *validate.Validation) {
v.WithScenes(validate.SValues{
"required": []string{"ID", "Kind"},
"pet": []string{"Settings.Pet"},
"human": []string{"Settings.Human"},
})
}
func TestPtrFieldEmbeddedValid(t *testing.T) {
// Valid case :)
input := []byte(`{
"id": "59fcf270-8646-4250-b4ff-d50f6121bc9d",
"kind": "pet",
"settings": {
"breed": "dog",
"color": "brown"
}
}`)
var entity Entity
err := json.Unmarshal(input, &entity)
fmt.Println(entity)
assert.NoError(t, err)
validate.Config(func(opt *validate.GlobalOption) {
opt.SkipOnEmpty = false
opt.StopOnError = false
})
vld := validate.Struct(&entity)
vld.SkipOnEmpty = false
err = vld.ValidateE("required")
assert.Empty(t, err)
vld.ResetResult()
err = vld.ValidateE(entity.Kind)
assert.Empty(t, err)
validate.ResetOption()
}
func TestPtrFieldEmbeddedInvalid(t *testing.T) {
// Invalid case
input := []byte(`{
"id": "59fcf270-8646-4250-b4ff-d50f6121bc9d",
"kind": "pet",
"settings": {
}
}`)
var entity Entity
err := json.Unmarshal(input, &entity)
fmt.Println(entity)
assert.NoError(t, err)
validate.Config(func(opt *validate.GlobalOption) {
opt.SkipOnEmpty = false
opt.StopOnError = false
})
vld := validate.Struct(&entity)
err = vld.ValidateE("required")
assert.Empty(t, err)
vld.ResetResult()
err = vld.ValidateE(entity.Kind)
expected := validate.Errors{
"breed": validate.MS{
"min_len": "breed min length is 3",
},
"color": validate.MS{
"in": "color value must be in the enum [orange black brown]",
},
}
assert.Equal(t, expected, err)
validate.ResetOption()
}
// ----- test case structs
type Org struct {
Company string `validate:"in:A,B,C,D"`
}
type Info struct {
Email string `validate:"email" filter:"trim|lower"`
Age *int `validate:"in:1,2,3,4"`
}
// anonymous struct nested
type User struct {
*Info `validate:"required"`
Org
Name string `validate:"required|string" filter:"trim|lower"`
Sex string `validate:"string"`
Time time.Time
}
// non-anonymous struct nested
type User2 struct {
Name string `validate:"required|string" filter:"trim|lower"`
In Info
Sex string `validate:"string"`
Time time.Time
}
type Info2 struct {
Org
Sub *Info
}
// gt 2 level struct nested
type User3 struct {
In2 *Info2 `validate:"required"`
}
// https://github.com/gookit/validate/issues/58
func TestStructNested(t *testing.T) {
// anonymous field test
age := 3
u := &User{
Name: "fish",
Info: &Info{
Email: "[email protected]",
Age: &age,
},
Org: Org{Company: "E"},
Sex: "male",
Time: time.Now(),
}
// anonymous field test
v := validate.Struct(u)
if v.Validate() {
assert.True(t, v.Validate())
} else {
// Print error msg,verify valid
fmt.Println("--- anonymous field test\n", v.Errors)
assert.False(t, v.Validate())
}
// non-anonymous field test
age = 3
user2 := &User2{
Name: "fish",
In: Info{
Email: "[email protected]",
Age: &age,
},
Sex: "male",
Time: time.Now(),
}
v2 := validate.Struct(user2)
if v2.Validate() {
assert.True(t, v2.Validate())
} else {
// Print error msg,verify valid
fmt.Printf("%v\n", v2.Errors)
assert.False(t, v2.Validate())
}
}
func TestStruct_nilPtr_field(t *testing.T) {
u1 := &User{
Name: "fish",
Info: nil,
Org: Org{Company: "C"},
Sex: "male",
}
v := validate.Struct(u1)
assert.False(t, v.Validate())
assert.Contains(t, v.Errors.String(), "Info is required")
fmt.Println(v.Errors)
}
func TestStructNested_gt2level(t *testing.T) {
age := 3
u := &User3{
In2: &Info2{
Org: Org{Company: "E"},
Sub: &Info{
Email: "[email protected] ",
Age: &age,
},
},
}
v := validate.Struct(u)
ok := v.Validate()
assert.False(t, ok)
assert.Equal(t, "In2.Org.Company value must be in the enum [A B C D]", v.Errors.Random())
fmt.Println(v.Errors)
u.In2.Org.Company = "A"
v = validate.Struct(u)
ok = v.Validate()
assert.True(t, ok)
assert.Equal(t, "[email protected]", u.In2.Sub.Email)
}
// https://github.com/gookit/validate/issues/76
func TestIssues_76(t *testing.T) {
type CategoryReq struct {
Name string
}
type Issue76 struct {
IsPrivate bool `json:"is_private"`
Categories []*CategoryReq `json:"categories" validate:"required_if:IsPrivate,false"`
}
v := validate.Struct(&Issue76{})
ok := v.Validate()
assert.False(t, ok)
dump.Println(v.Errors)
assert.Equal(t, "categories is required when is_private is in [false]", v.Errors.One())
v = validate.Struct(&Issue76{Categories: []*CategoryReq{
{Name: "book"},
}})
ok = v.Validate()
assert.True(t, ok)
// test convert to bool error
type Issue76A struct {
IsPrivate bool `json:"is_private"`
Categories []*CategoryReq `json:"categories" validate:"required_if:IsPrivate,invalid"`
}
v = validate.Struct(&Issue76A{})
ok = v.Validate()
assert.True(t, ok)
}
// https://github.com/gookit/validate/issues/78
func TestIssue_78(t *testing.T) {
type UserDto struct {
Name string `validate:"required"`
Sex *bool `validate:"required"`
}
// sex := true
u := UserDto{
Name: "abc",
Sex: nil,
}
// 创建 Validation 实例
v := validate.Struct(&u)
ok := v.Validate()
assert.False(t, ok)
assert.Equal(t, "Sex is required to not be empty", v.Errors.One())
sex := false
u = UserDto{
Name: "abc",
Sex: &sex,
}
v = validate.Struct(&u)
ok = v.Validate()
assert.True(t, ok)
}
// https://gitee.com/inhere/validate/issues/I36T2B
func TestIssues_I36T2B(t *testing.T) {
m := map[string]any{
"a": 0,
}
// 创建 Validation 实例
v := validate.Map(m)
v.AddRule("a", "gt", 100)
ok := v.Validate()
assert.True(t, ok)
v = validate.Map(m)
v.AddRule("a", "gt", 100).SetSkipEmpty(false)
ok = v.Validate()
assert.False(t, ok)
assert.Equal(t, "a value should be greater than 100", v.Errors.One())
v = validate.Map(m)
v.AddRule("a", "required")
v.AddRule("a", "gt", 100)
ok = v.Validate()
assert.False(t, ok)
assert.Equal(t, "a is required to not be empty", v.Errors.One())
}
// https://gitee.com/inhere/validate/issues/I3B3AV
func TestIssues_I3B3AV(t *testing.T) {
m := map[string]any{
"a": 0.01,
"b": float32(0.03),
}
v := validate.Map(m)
v.AddRule("a", "gt", 0)
v.AddRule("b", "gt", 0)
assert.True(t, v.Validate())
}
// https://github.com/gookit/validate/issues/92
func TestIssues_92(t *testing.T) {
m := map[string]any{
"t": 1.1,
}
v := validate.Map(m)
v.FilterRule("t", "float")
ok := v.Validate()
assert.True(t, ok)
}
// https://github.com/gookit/validate/issues/98
func TestIssues_98(t *testing.T) {
// MenuActionResource 菜单动作关联资源对象
type MenuActionResource struct {
ID uint64 `json:"id"` // 唯一标识
ActionID uint64 `json:"action_id"` // 菜单动作ID
Method string `json:"method" validate:"required"` // 资源请求方式(支持正则)
Path string `json:"path" validate:"required"` // 资源请求路径(支持/:id匹配)
}
// MenuActionResources 菜单动作关联资源管理列表
type MenuActionResources []*MenuActionResource
// MenuAction 菜单动作对象
type MenuAction struct {
Code string `json:"code" validate:"required"` // 动作编号
Name string `json:"name" validate:"required"` // 动作名称
Resources MenuActionResources `json:"resources,omitempty"` // 资源列表
}
// MenuActions 菜单动作管理列表
type MenuActions []*MenuAction
type MenuCreateRequest struct {
Name string `json:"name" validate:"required"`
Sequence int `json:"sequence"` // 排序值
Icon string `json:"icon"` // 菜单图标
Router string `json:"router"` // 访问路由
ParentID uint64 `json:"parent_id"` // 父级ID
IsShow int `json:"is_show" validate:"in:0,1"` // 是否显示(1:显示 0:隐藏)
Status int `json:"status" validate:"in:0,1"` // 状态(1:启用 0:禁用)
Memo string `json:"memo"` // 备注
MenuActions MenuActions `json:"actions,omitempty"`
}
req := &MenuCreateRequest{
Name: "users",
MenuActions: []*MenuAction{
{
Code: "code01",
Name: "name01",
Resources: []*MenuActionResource{
{
Method: "get",
Path: "/home",
},
},
},
},
}
v := validate.Struct(req)
ok := v.Validate()
dump.Println(v.Errors)
assert.True(t, ok)
}
// https://github.com/gookit/validate/issues/103
func TestIssues_103(t *testing.T) {
type Example struct {
SomeID string `validate:"required"`
}
o := Example{}
v := validate.Struct(o)
v.Validate()
// here we get something like {"SomeID": { /* ... */ }}
m := v.Errors.All()
// dump.Println(m)
assert.Contains(t, m, "SomeID")
assert.Contains(t, v.Errors.String(), "SomeID is required to not be empty")
type Example2 struct {
SomeID string `json:"some_id" validate:"required" `
}
e2 := Example2{}
v2 := validate.Struct(e2)
v2.Validate()
dump.Println(v2.Errors)
err2 := v2.Errors.String() // here we get something like {"some_id": { /* ... */ }}
assert.Contains(t, err2, "some_id")
assert.Contains(t, err2, "some_id is required to not be empty")
}
type Issue104A struct {
ID int `json:"id" gorm:"primarykey" form:"id" validate:"int|required"`
}
type Issue104Demo struct {
Issue104A
Title string `json:"title" form:"title" validate:"required" example:"123456"` // 任务id
}
// GetScene 定义验证场景
// func (d Issue104Demo) GetScene() validate.SValues {
// return validate.SValues{
// "add": []string{"ID", "Title"},
// "update": []string{"ID", "Title"},
// }
// }
// ConfigValidation 配置验证
// - 定义验证场景
func (d Issue104Demo) ConfigValidation(v *validate.Validation) {
v.WithScenes(validate.SValues{
"add": []string{"Issue104A.ID", "Title"},
"update": []string{"Issue104A.ID", "Title"},
})
}
// https://github.com/gookit/validate/issues/104
func TestIssues_104(t *testing.T) {
d := &Issue104Demo{
Issue104A: Issue104A{
ID: 0,
},
Title: "abc",
}
v := validate.Struct(d)
ok := v.Validate()
dump.Println(v.Errors)
assert.False(t, ok)
assert.Equal(t, "id is required to not be empty", v.Errors.One())
v = validate.Struct(d, "add")
ok = v.Validate()
dump.Println(v.Errors, v.SceneFields())
assert.False(t, ok)
assert.Equal(t, "add", v.Scene())
assert.Equal(t, "id is required to not be empty", v.Errors.One())
// right
d.Issue104A.ID = 34
v = validate.Struct(d)
ok = v.Validate()
assert.True(t, ok)
}
// https://github.com/gookit/validate/issues/107
func TestIssues_107(t *testing.T) {
taFilter := func(val any) int64 {
if val != nil {
// log.WithFields(log.Fields{"value": val}).Info("value should be other than nil")
return int64(val.(float64))
}
// log.WithFields(log.Fields{"value": val}).Info("value should be nil")
return -1
}
v := validate.Map(map[string]any{
"tip_amount": float64(12),
})
v.AddFilter("tip_amount_filter", taFilter)
// method 1:
// v.FilterRule("tip_amount", "tip_amount_filter")
// v.AddRule("tip_amount", "int")
// method 2:
v.StringRule("tip_amount", "int", "tip_amount_filter")
assert.Equal(t, float64(12), v.RawVal("tip_amount"))
// call validate
assert.True(t, v.Validate())
// dump.Println(v.FilteredData())
dump.Println(v.SafeData())
assert.Equal(t, int64(12), v.SafeVal("tip_amount"))
}
// https://github.com/gookit/validate/issues/111
func TestIssues_111(t *testing.T) {
v := validate.New(map[string]any{
"username": "inhere",
"password": "h9i8tssx9153",
"password2": "h9i8XYZ9153",
})
v.AddTranslates(map[string]string{
"username": "账号",
"password": "密码",
"password2": "重复密码",
})
v.StringRule("username", "required")
v.StringRule("password", "required|eq_field:password2|minLen:6|max_len:32")
assert.False(t, v.Validate())
dump.Println(v.Errors)
assert.Contains(t, v.Errors.String(), "密码 ")
assert.Contains(t, v.Errors.String(), " 重复密码")
}
// https://github.com/gookit/validate/issues/120
func TestIssues_120(t *testing.T) {
type ThirdStruct struct {
Val string `json:"val" validate:"required"`
}
type SecondStruct struct {
Third []ThirdStruct `json:"third" validate:"slice"`
}
type MainStruct struct {
Second []SecondStruct `json:"second" validate:"slice"`
}
v := validate.Struct(&MainStruct{
Second: []SecondStruct{
{
Third: []ThirdStruct{
{
Val: "hello",
},
},
},
},
})
ok := v.Validate()
assert.True(t, ok)
// dump.Println(v.Errors)
}
// https://github.com/gookit/validate/issues/124
// Validate array/slice items #124
func TestIssue_124(t *testing.T) {
m := map[string]any{
"names": []string{"John", "Jane", "abc"},
"address": []map[string]string{
{"number": "1b", "country": "en"},
{"number": "1", "country": "cz"},
},
}
v := validate.Map(m)
v.StopOnError = false
// simple slices
v.StringRule("names", "required|array|minLen:1")
v.StringRule("names.*", "required|string|min_len:4")
// slices of maps
v.StringRule("address.*.number", "required|int")
v.StringRule("address.*.country", "required|in:es,us")
assert.False(t, v.Validate())
assert.Error(t, v.Errors.ErrOrNil())
assert.Equal(t, len(v.Errors.All()), 3)
assert.Equal(t, "names.* min length is 4", v.Errors.Field("names.*")["min_len"])
assert.Equal(t, "address.*.number value must be an integer", v.Errors.Field("address.*.number")["int"])
assert.Equal(t, "address.*.country value must be in the enum [es us]", v.Errors.Field("address.*.country")["in"])
// dump.Println(v.Errors)
// TODO how to use on struct.
// type user struct {
// Tags []string `json:"tags" validate:"required|slice"`
// }
}
// https://github.com/gookit/validate/issues/125
func TestIssue_125(t *testing.T) {
defer validate.ResetOption()
validate.Config(func(opt *validate.GlobalOption) {
opt.SkipOnEmpty = false
})
validate.AddValidator("custom", func(value any) bool {
// validation...
return true
})
v := validate.Map(map[string]any{
"field": nil,
})
v.StringRule("field", "custom")
assert.True(t, v.Validate())
var val *int
v2 := validate.Map(map[string]any{
"field": val,
})
v2.StringRule("field", "custom")
assert.True(t, v2.Validate())
}
// https://github.com/gookit/validate/issues/135
func TestIssue_135(t *testing.T) {
type SubjectCreateReq struct {
Title string `json:"title" validate:"required|minLen:2|maxLen:512"` // 题目名称
SubjectType string `json:"subject_type" validate:"required|in:radio,checkbox,bool"` // 题目类型
Answer []struct {
Score float64 `json:"score" validate:"required|min:0.1"` // 得分
Metas string `json:"metas" validate:"required|minLen:2"` // 元信息
} `json:"answer"` // 答案
}
s := `
{
"title":"44",
"answer":[
{
"score":0.09,
"metas":"111"
}
],
"subject_type":"radio"
}`
r := &SubjectCreateReq{}
err := jsonutil.Decode([]byte(s), r)
assert.NoError(t, err)
// dump.Println(r)
v := validate.Struct(r)
ok := v.Validate()
dump.Println(v.Errors)
assert.False(t, ok)
assert.Equal(t, "score min value is 0.1", v.Errors.One())
assert.Equal(t, "score min value is 0.1", v.Errors.OneError().Error())
}
// https://github.com/gookit/validate/issues/140
func TestIssue_140(t *testing.T) {
type Test struct {
Field1 string
Field2 string `validate:"requiredIf:Field1,value"`
}
test := &Test{Field1: "value", Field2: ""}
v := validate.Struct(test)
err := v.ValidateE()
dump.Println(err)
assert.Error(t, err)
assert.Equal(t, "Field2 is required when Field1 is in [value]", err.One())
test.Field2 = "hi"
v = validate.Struct(test)
err = v.ValidateE()
assert.Nil(t, err)
}
// https://github.com/gookit/validate/issues/143
func TestIssue_143(t *testing.T) {
type Data struct {
Name string `validate:"required"`
Age *int `json:"age" validate:"required"`
}
v := validate.New(&Data{
Name: "tom",
Age: nil,
})
ok := v.Validate()
assert.False(t, ok)
assert.Equal(t, "age is required to not be empty", v.Errors.One())
// use ptr
age := 0
v = validate.New(&Data{