-
Notifications
You must be signed in to change notification settings - Fork 116
/
validators.go
1269 lines (1053 loc) · 30.1 KB
/
validators.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
import (
"bytes"
"encoding/json"
"net"
"net/url"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gookit/goutil/arrutil"
"github.com/gookit/goutil/fsutil"
"github.com/gookit/goutil/mathutil"
"github.com/gookit/goutil/strutil"
)
// Basic regular expressions for validating strings.
// (there are from package "asaskevich/govalidator")
const (
Email = `^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$`
UUID3 = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$"
UUID4 = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
UUID5 = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
UUID = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$"
Int = "^(?:[-+]?(?:0|[1-9][0-9]*))$"
Float = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$"
RGBColor = "^rgb\\(\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*,\\s*(0|[1-9]\\d?|1\\d\\d?|2[0-4]\\d|25[0-5])\\s*\\)$"
FullWidth = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
HalfWidth = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]"
Base64 = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$"
Latitude = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$"
Longitude = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$"
DNSName = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$`
FullURL = `^(?:ftp|tcp|udp|wss?|https?):\/\/[\w\.\/#=?&-_%]+$`
URLSchema = `((ftp|tcp|udp|wss?|https?):\/\/)`
URLUsername = `(\S+(:\S*)?@)`
URLPath = `((\/|\?|#)[^\s]*)`
URLPort = `(:(\d{1,5}))`
URLIP = `([1-9]\d?|1\d\d|2[01]\d|22[0-3])(\.(1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-4]))`
URLSubdomain = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))`
WinPath = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$`
UnixPath = `^(/[^/\x00]*)+/?$`
)
// some string regexp. (it is from package "asaskevich/govalidator")
var (
// rxUser = regexp.MustCompile("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~.-]+$")
// rxHostname = regexp.MustCompile("^[^\\s]+\\.[^\\s]+$")
// rxUserDot = regexp.MustCompile("(^[.]{1})|([.]{1}$)|([.]{2,})")
rxEmail = regexp.MustCompile(Email)
rxISBN10 = regexp.MustCompile(`^(?:\d{9}X|\d{10})$`)
rxISBN13 = regexp.MustCompile(`^\d{13}$`)
rxUUID3 = regexp.MustCompile(UUID3)
rxUUID4 = regexp.MustCompile(UUID4)
rxUUID5 = regexp.MustCompile(UUID5)
rxUUID = regexp.MustCompile(UUID)
rxAlpha = regexp.MustCompile("^[a-zA-Z]+$")
rxAlphaNum = regexp.MustCompile("^[a-zA-Z0-9]+$")
rxAlphaDash = regexp.MustCompile(`^(?:[\w-]+)$`)
rxNumber = regexp.MustCompile("^[0-9]+$")
rxInt = regexp.MustCompile(Int)
rxFloat = regexp.MustCompile(Float)
rxCnMobile = regexp.MustCompile(`^1\d{10}$`)
rxHexColor = regexp.MustCompile(`^#?([\da-fA-F]{3}|[\da-fA-F]{6})$`)
rxRGBColor = regexp.MustCompile(RGBColor)
rxASCII = regexp.MustCompile("^[\x00-\x7F]+$")
// --
rxHexadecimal = regexp.MustCompile(`^[\da-fA-F]+$`)
rxPrintableASCII = regexp.MustCompile("^[\x20-\x7E]+$")
rxMultiByte = regexp.MustCompile("[^\x00-\x7F]")
// rxFullWidth = regexp.MustCompile(FullWidth)
// rxHalfWidth = regexp.MustCompile(HalfWidth)
rxBase64 = regexp.MustCompile(Base64)
rxDataURI = regexp.MustCompile(`^data:.+/(.+);base64,(?:.+)`)
rxLatitude = regexp.MustCompile(Latitude)
rxLongitude = regexp.MustCompile(Longitude)
rxDNSName = regexp.MustCompile(DNSName)
rxFullURL = regexp.MustCompile(FullURL)
rxURLSchema = regexp.MustCompile(URLSchema)
// rxSSN = regexp.MustCompile(`^\d{3}[- ]?\d{2}[- ]?\d{4}$`)
rxWinPath = regexp.MustCompile(WinPath)
rxUnixPath = regexp.MustCompile(UnixPath)
// --
rxHasLowerCase = regexp.MustCompile(".*[[:lower:]]")
rxHasUpperCase = regexp.MustCompile(".*[[:upper:]]")
)
/*************************************************************
* global validators
*************************************************************/
type funcMeta struct {
fv reflect.Value
// validator name
name string
// readonly cache
numIn int
numOut int
// is internal built-in validator
builtin bool
// last arg is variadic param. like "... any"
isVariadic bool
}
func (fm *funcMeta) checkArgNum(argNum int, name string) {
// last arg is like "... any"
if fm.isVariadic {
if argNum+1 < fm.numIn {
panicf("not enough parameters for validator '%s'!", name)
}
} else if argNum != fm.numIn {
panicf(
"the number of parameters given does not match the required. validator '%s', want %d, given %d",
name,
fm.numIn,
argNum,
)
}
}
func newFuncMeta(name string, builtin bool, fv reflect.Value) *funcMeta {
fm := &funcMeta{fv: fv, name: name, builtin: builtin}
ft := fv.Type()
fm.numIn = ft.NumIn() // arg num of the func
fm.numOut = ft.NumOut() // return arg num of the func
fm.isVariadic = ft.IsVariadic()
return fm
}
// ValidatorName get real validator name.
func ValidatorName(name string) string {
if rName, ok := validatorAliases[name]; ok {
return rName
}
return name
}
// AddValidators to the global validators map
func AddValidators(m map[string]any) {
for name, checkFunc := range m {
AddValidator(name, checkFunc)
}
}
// AddValidator to the pkg. checkFunc must return a bool
//
// Usage:
//
// v.AddValidator("myFunc", func(val any) bool {
// // do validate val ...
// return true
// })
func AddValidator(name string, checkFunc any) {
fv := checkValidatorFunc(name, checkFunc)
validators[name] = validatorTypeCustom
// validatorValues[name] = fv
validatorMetas[name] = newFuncMeta(name, false, fv)
}
// Validators get all validator names
func Validators() map[string]int8 {
return validators
}
/*************************************************************
* context validators:
* - field value compare
* - requiredXXX
*************************************************************/
// Required field val check
func (v *Validation) Required(field string, val any) bool {
if v.isInOptional(field) {
return true
}
if v.data != nil && v.data.Type() == sourceForm {
// check is upload file
if v.data.(*FormData).HasFile(field) {
return true
}
}
// check value
return !IsEmpty(val)
}
// RequiredIf field under validation must be present and not empty,
// if the anotherField field is equal to any value.
//
// Usage:
//
// v.AddRule("password", "requiredIf", "username", "tom")
func (v *Validation) RequiredIf(_ string, val any, kvs ...string) bool {
if len(kvs) < 2 {
return false
}
dstField, args := kvs[0], kvs[1:]
if dstVal, has := v.Get(dstField); has {
// up: only one check value, direct compare value
if len(args) == 1 {
rftDv := reflect.ValueOf(dstVal)
wantVal, err := convTypeByBaseKind(args[0], stringKind, rftDv.Kind())
if err == nil && dstVal == wantVal {
return val != nil && !IsEmpty(val)
}
} else if Enum(dstVal, args) {
return val != nil && !IsEmpty(val)
}
}
// default as True, skip check
return true
}
// RequiredUnless field under validation must be present and not empty
// unless the dstField field is equal to any value.
//
// - kvs format: [dstField, dstVal1, dstVal2 ...]
func (v *Validation) RequiredUnless(_ string, val any, kvs ...string) bool {
if len(kvs) < 2 {
return false
}
dstField, values := kvs[0], kvs[1:]
if dstVal, has, _ := v.tryGet(dstField); has {
if !Enum(dstVal, values) {
return !IsEmpty(val)
}
}
// fields in values
return true
}
// RequiredWith field under validation must be present and not empty only
// if any of the other specified fields are present.
//
// - fields format: [field1, field2 ...]
func (v *Validation) RequiredWith(_ string, val any, fields ...string) bool {
if len(fields) == 0 {
return false
}
for _, field := range fields {
if _, has, zero := v.tryGet(field); has && !zero {
return !IsEmpty(val)
}
}
// all fields not exist
return true
}
// RequiredWithAll field under validation must be present and not empty only if all the other specified fields are present.
func (v *Validation) RequiredWithAll(_ string, val any, fields ...string) bool {
if len(fields) == 0 {
return false
}
for _, field := range fields {
if _, has, zero := v.tryGet(field); !has || zero {
// if any field does not exist, not continue.
return true
}
}
// all fields exist
return !IsEmpty(val)
}
// RequiredWithout field under validation must be present and not empty only when any of the other specified fields are not present.
func (v *Validation) RequiredWithout(_ string, val any, fields ...string) bool {
if len(fields) == 0 {
return false
}
for _, field := range fields {
if _, has, zero := v.tryGet(field); !has || zero {
return !IsEmpty(val)
}
}
// all fields exist
return true
}
// RequiredWithoutAll field under validation must be present and not empty only when any of the other specified fields are not present.
func (v *Validation) RequiredWithoutAll(_ string, val any, fields ...string) bool {
if len(fields) == 0 {
return false
}
for _, name := range fields {
// if any field exist, not continue.
if _, has, zero := v.tryGet(name); has && !zero {
return true
}
}
// all fields not exist, required
return !IsEmpty(val)
}
// EqField value should EQ the dst field value
func (v *Validation) EqField(val any, dstField string) bool {
// get dst field value.
dstVal, has := v.Get(dstField)
if !has {
return false
}
return IsEqual(val, dstVal)
}
// NeField value should not equal the dst field value
func (v *Validation) NeField(val any, dstField string) bool {
dstVal, has := v.Get(dstField)
if !has {
return false
}
return !IsEqual(val, dstVal)
}
// GtField value should GT the dst field value
func (v *Validation) GtField(val any, dstField string) bool {
// get dst field value.
dstVal, has := v.Get(dstField)
if !has {
return false
}
return valueCompare(val, dstVal, ">")
}
// GteField value should GTE the dst field value
func (v *Validation) GteField(val any, dstField string) bool {
dstVal, has := v.Get(dstField)
if !has {
return false
}
return valueCompare(val, dstVal, ">=")
}
// LtField value should LT the dst field value
func (v *Validation) LtField(val any, dstField string) bool {
// get dst field value.
dstVal, has := v.Get(dstField)
if !has {
return false
}
return valueCompare(val, dstVal, "<")
}
// LteField value should LTE the dst field value(for int, string)
func (v *Validation) LteField(val any, dstField string) bool {
// get dst field value.
dstVal, has := v.Get(dstField)
if !has {
return false
}
return valueCompare(val, dstVal, "<=")
}
/*************************************************************
* context validators:
* - file validators
*************************************************************/
const fileValidators = "|isFile|isImage|inMimeTypes|"
var (
imageMimeTypes = map[string]string{
"bmp": "image/bmp",
"gif": "image/gif",
"ief": "image/ief",
"jpg": "image/jpeg",
// "jpe": "image/jpeg",
"jpeg": "image/jpeg",
"png": "image/png",
"svg": "image/svg+xml",
"ico": "image/x-icon",
"webp": "image/webp",
}
)
func isFileValidator(name string) bool {
return strings.Contains(fileValidators, "|"+name+"|")
}
// IsFormFile check field is uploaded file
func (v *Validation) IsFormFile(fd *FormData, field string) (ok bool) {
if fh := fd.GetFile(field); fh != nil {
_, err := fh.Open()
if err == nil {
return true
}
}
return false
}
// IsFormImage check field is uploaded image file.
// Usage:
//
// v.AddRule("avatar", "image")
// v.AddRule("avatar", "image", "jpg", "png", "gif") // set ext limit
func (v *Validation) IsFormImage(fd *FormData, field string, exts ...string) (ok bool) {
mime := fd.FileMimeType(field)
if mime == "" {
return
}
var fileExt string
for ext, imgMime := range imageMimeTypes {
if imgMime == mime {
fileExt = ext
ok = true
break
}
}
// don't limit mime type
if len(exts) == 0 {
return ok // only check is an image
}
return Enum(fileExt, exts)
}
// InMimeTypes check field is uploaded file and mime type is in the mimeTypes.
// Usage:
//
// v.AddRule("video", "mimeTypes", "video/avi", "video/mpeg", "video/quicktime")
func (v *Validation) InMimeTypes(fd *FormData, field, mimeType string, moreTypes ...string) bool {
mime := fd.FileMimeType(field)
if mime == "" {
return false
}
mimeTypes := append(moreTypes, mimeType) //nolint:gocritic
return Enum(mime, mimeTypes)
}
/*************************************************************
* global: basic validators
*************************************************************/
// IsEmpty of the value
func IsEmpty(val any) bool {
if val == nil {
return true
}
if s, ok := val.(string); ok {
return s == ""
}
return ValueIsEmpty(reflect.ValueOf(val))
}
// Contains check that the specified string, list(array, slice) or map contains the
// specified substring or element.
//
// Notice: list check value exist. map check key exist.
func Contains(s, sub any) bool {
ok, found := includeElement(s, sub)
// ok == false: 's' could not be applied builtin len()
// found == false: 's' does not contain 'sub'
return ok && found
}
// NotContains check that the specified string, list(array, slice) or map does NOT contain the
// specified substring or element.
//
// Notice: list check value exist. map check key exist.
func NotContains(s, sub any) bool {
ok, found := includeElement(s, sub)
// ok == false: could not be applied builtin len()
// found == true: 's' contain 'sub'
return ok && !found
}
/*************************************************************
* global: type validators
*************************************************************/
// IsUint check, allow: intX, uintX, string
func IsUint(val any) bool {
switch typVal := val.(type) {
case int:
return typVal >= 0
case int8:
return typVal >= 0
case int16:
return typVal >= 0
case int32:
return typVal >= 0
case int64:
return typVal >= 0
case uint, uint8, uint16, uint32, uint64:
return true
case string:
_, err := strconv.ParseUint(typVal, 10, 32)
return err == nil
}
return false
}
// IsBool check. allow: bool, string.
func IsBool(val any) bool {
val = indirectValue(val)
if _, ok := val.(bool); ok {
return true
}
if typVal, ok := val.(string); ok {
_, err := strutil.ToBool(typVal)
return err == nil
}
return false
}
// IsFloat check. allow: floatX, string
func IsFloat(val any) bool {
val = indirectValue(val)
if val == nil {
return false
}
switch rv := val.(type) {
case float32, float64:
return true
case string:
return rv != "" && rxFloat.MatchString(rv)
}
return false
}
// IsArray check value is array or slice.
func IsArray(val any, strict ...bool) (ok bool) {
if val == nil {
return false
}
rv := reflect.Indirect(reflect.ValueOf(val))
// strict: must go array type.
if len(strict) > 0 && strict[0] {
return rv.Kind() == reflect.Array
}
// allow array, slice
return rv.Kind() == reflect.Array || rv.Kind() == reflect.Slice
}
// IsSlice check value is slice type
func IsSlice(val any) (ok bool) {
if val == nil {
return false
}
rv := reflect.Indirect(reflect.ValueOf(val))
return rv.Kind() == reflect.Slice
}
// IsInts is int slice check
func IsInts(val any) bool {
if val == nil {
return false
}
switch val.(type) {
case []int, []int8, []int16, []int32, []int64, []uint, []uint8, []uint16, []uint32, []uint64:
return true
}
return false
}
// IsStrings is string slice check
func IsStrings(val any) (ok bool) {
if val == nil {
return false
}
_, ok = val.([]string)
return
}
// IsMap check
func IsMap(val any) (ok bool) {
if val == nil {
return false
}
rv := reflect.Indirect(reflect.ValueOf(val))
return rv.Kind() == reflect.Map
}
// IsInt check, and support length check
func IsInt(val any, minAndMax ...int64) (ok bool) {
val = indirectValue(val)
if val == nil {
return false
}
intVal, err := valueToInt64(val, true)
if err != nil {
return false
}
argLn := len(minAndMax)
if argLn == 0 { // only check type
return true
}
// value check
minVal := minAndMax[0]
if argLn == 1 { // only min length check.
return intVal >= minVal
}
// min and max length check
return intVal >= minVal && intVal <= minAndMax[1]
}
// IsString check and support length check.
//
// Usage:
//
// ok := IsString(val)
// ok := IsString(val, 5) // with min len check
// ok := IsString(val, 5, 12) // with min and max len check
func IsString(val any, minAndMaxLen ...int) (ok bool) {
val = indirectValue(val)
if val == nil {
return false
}
argLn := len(minAndMaxLen)
str, isStr := val.(string)
// only check type
if argLn == 0 {
return isStr
}
if !isStr {
return false
}
// length check
strLen := len(str)
minLen := minAndMaxLen[0]
// only min length check.
if argLn == 1 {
return strLen >= minLen
}
// min and max length check
return strLen >= minLen && strLen <= minAndMaxLen[1]
}
/*************************************************************
* global: string validators
*************************************************************/
// HasWhitespace check. eg "10"
func HasWhitespace(s string) bool {
return s != "" && strings.ContainsRune(s, ' ')
}
// IsIntString check. eg "10"
func IsIntString(s string) bool {
return s != "" && rxInt.MatchString(s)
}
// IsASCII string.
func IsASCII(s string) bool {
return s != "" && rxASCII.MatchString(s)
}
// IsPrintableASCII string.
func IsPrintableASCII(s string) bool {
return s != "" && rxPrintableASCII.MatchString(s)
}
// IsBase64 string.
func IsBase64(s string) bool {
return s != "" && rxBase64.MatchString(s)
}
// IsLatitude string.
func IsLatitude(s string) bool {
return s != "" && rxLatitude.MatchString(s)
}
// IsLongitude string.
func IsLongitude(s string) bool {
return s != "" && rxLongitude.MatchString(s)
}
// IsDNSName string.
func IsDNSName(s string) bool {
return s != "" && rxDNSName.MatchString(s)
}
// HasURLSchema string.
func HasURLSchema(s string) bool {
return s != "" && rxURLSchema.MatchString(s)
}
// IsFullURL string.
func IsFullURL(s string) bool {
return s != "" && rxFullURL.MatchString(s)
}
// IsURL string.
func IsURL(s string) bool {
if s == "" {
return false
}
_, err := url.Parse(s)
return err == nil
}
// IsDataURI string.
//
// data:[<mime type>] ( [;charset=<charset>] ) [;base64],码内容
// eg. "data:image/gif;base64,R0lGODlhA..."
func IsDataURI(s string) bool {
return s != "" && rxDataURI.MatchString(s)
}
// IsMultiByte string.
func IsMultiByte(s string) bool {
return s != "" && rxMultiByte.MatchString(s)
}
// IsISBN10 string.
func IsISBN10(s string) bool {
return s != "" && rxISBN10.MatchString(s)
}
// IsISBN13 string.
func IsISBN13(s string) bool {
return s != "" && rxISBN13.MatchString(s)
}
// IsHexadecimal string.
func IsHexadecimal(s string) bool {
return s != "" && rxHexadecimal.MatchString(s)
}
// IsCnMobile string.
func IsCnMobile(s string) bool {
return s != "" && rxCnMobile.MatchString(s)
}
// IsHexColor string.
func IsHexColor(s string) bool {
return s != "" && rxHexColor.MatchString(s)
}
// IsRGBColor string.
func IsRGBColor(s string) bool {
return s != "" && rxRGBColor.MatchString(s)
}
// IsAlpha string.
func IsAlpha(s string) bool {
return s != "" && rxAlpha.MatchString(s)
}
// IsAlphaNum string.
func IsAlphaNum(s string) bool {
return s != "" && rxAlphaNum.MatchString(s)
}
// IsAlphaDash string.
func IsAlphaDash(s string) bool {
return s != "" && rxAlphaDash.MatchString(s)
}
// IsNumber string. should >= 0
func IsNumber(v any) bool {
v = indirectValue(v)
if v == nil {
return false
}
if s, err := strutil.ToString(v); err == nil {
return s != "" && rxNumber.MatchString(s)
}
return false
}
// IsNumeric is string/int number. should >= 0
func IsNumeric(v any) bool {
v = indirectValue(v)
if v == nil {
return false
}
if s, err := strutil.ToString(v); err == nil {
return s != "" && rxNumber.MatchString(s)
}
return false
}
// IsStringNumber is string number. should >= 0
func IsStringNumber(s string) bool {
return s != "" && rxNumber.MatchString(s)
}
// IsEmail check
func IsEmail(s string) bool { return s != "" && rxEmail.MatchString(s) }
// IsUUID string
func IsUUID(s string) bool { return s != "" && rxUUID.MatchString(s) }
// IsUUID3 string
func IsUUID3(s string) bool { return s != "" && rxUUID3.MatchString(s) }
// IsUUID4 string
func IsUUID4(s string) bool { return s != "" && rxUUID4.MatchString(s) }
// IsUUID5 string
func IsUUID5(s string) bool { return s != "" && rxUUID5.MatchString(s) }
// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
func IsIP(s string) bool { return s != "" && net.ParseIP(s) != nil }
// IsIPv4 is the validation function for validating if a value is a valid v4 IP address.
func IsIPv4(s string) bool {
if s == "" {
return false
}
ip := net.ParseIP(s)
return ip != nil && ip.To4() != nil
}
// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
func IsIPv6(s string) bool {
ip := net.ParseIP(s)
return ip != nil && ip.To4() == nil
}
// IsMAC is the validation function for validating if the field's value is a valid MAC address.
func IsMAC(s string) bool {
if s == "" {
return false
}
_, err := net.ParseMAC(s)
return err == nil
}
// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
func IsCIDRv4(s string) bool {
if s == "" {
return false
}
ip, _, err := net.ParseCIDR(s)
return err == nil && ip.To4() != nil
}
// IsCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address.
func IsCIDRv6(s string) bool {
if s == "" {
return false
}
ip, _, err := net.ParseCIDR(s)
return err == nil && ip.To4() == nil
}
// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
func IsCIDR(s string) bool {
if s == "" {
return false
}
_, _, err := net.ParseCIDR(s)
return err == nil
}
// IsJSON check if the string is valid JSON (note: uses json.Unmarshal).
func IsJSON(s string) bool {
if s == "" {
return false
}
var js json.RawMessage
return Unmarshal([]byte(s), &js) == nil
}
// HasLowerCase check string has lower case
func HasLowerCase(s string) bool {
if s == "" {
return false
}
return rxHasLowerCase.MatchString(s)
}
// HasUpperCase check string has upper case
func HasUpperCase(s string) bool {
return s != "" && rxHasUpperCase.MatchString(s)
}
// StartsWith check string is starts with sub-string
func StartsWith(s, sub string) bool {
return s != "" && strings.HasPrefix(s, sub)
}
// EndsWith check string is ends with sub-string
func EndsWith(s, sub string) bool {
return s != "" && strings.HasSuffix(s, sub)
}
// StringContains check string is contains sub-string
func StringContains(s, sub string) bool {
return s != "" && strings.Contains(s, sub)
}
// Regexp match value string
func Regexp(str string, pattern string) bool {
ok, _ := regexp.MatchString(pattern, str)
return ok
}
/*************************************************************
* global: filesystem validators
*************************************************************/
// PathExists reports whether the named file or directory exists.
func PathExists(path string) bool {
return fsutil.PathExists(path)
}
// IsFilePath path is a local filepath
func IsFilePath(path string) bool {
return fsutil.IsFile(path)
}
// IsDirPath path is a local dir path
func IsDirPath(path string) bool {
return fsutil.IsDir(path)
}
// IsWinPath string
func IsWinPath(s string) bool {
return s != "" && rxWinPath.MatchString(s)
}
// IsUnixPath string
func IsUnixPath(s string) bool {
return s != "" && rxUnixPath.MatchString(s)
}
/*************************************************************
* global: compare validators
*************************************************************/
// IsEqual check two value is equals.
//
// Support:
//
// bool, int(X), uint(X), string, float(X) AND slice, array, map
func IsEqual(val, wantVal any) bool {
// check is nil
if val == nil || wantVal == nil {
return val == wantVal
}
sv := reflect.ValueOf(val)
wv := reflect.ValueOf(wantVal)
// don't compare func, struct
if sv.Kind() == reflect.Func || sv.Kind() == reflect.Struct {