podman
1474 строки · 38.2 Кб
1/*
2Package validator implements value validations for structs and individual fields
3based on tags.
4
5It can also handle Cross-Field and Cross-Struct validation for nested structs
6and has the ability to dive into arrays and maps of any type.
7
8see more examples https://github.com/go-playground/validator/tree/master/_examples
9
10# Singleton
11
12Validator is designed to be thread-safe and used as a singleton instance.
13It caches information about your struct and validations,
14in essence only parsing your validation tags once per struct type.
15Using multiple instances neglects the benefit of caching.
16The not thread-safe functions are explicitly marked as such in the documentation.
17
18# Validation Functions Return Type error
19
20Doing things this way is actually the way the standard library does, see the
21file.Open method here:
22
23https://golang.org/pkg/os/#Open.
24
25The authors return type "error" to avoid the issue discussed in the following,
26where err is always != nil:
27
28http://stackoverflow.com/a/29138676/3158232
29https://github.com/go-playground/validator/issues/134
30
31Validator only InvalidValidationError for bad validation input, nil or
32ValidationErrors as type error; so, in your code all you need to do is check
33if the error returned is not nil, and if it's not check if error is
34InvalidValidationError ( if necessary, most of the time it isn't ) type cast
35it to type ValidationErrors like so err.(validator.ValidationErrors).
36
37# Custom Validation Functions
38
39Custom Validation functions can be added. Example:
40
41// Structure
42func customFunc(fl validator.FieldLevel) bool {
43
44if fl.Field().String() == "invalid" {
45return false
46}
47
48return true
49}
50
51validate.RegisterValidation("custom tag name", customFunc)
52// NOTES: using the same tag name as an existing function
53// will overwrite the existing one
54
55# Cross-Field Validation
56
57Cross-Field Validation can be done via the following tags:
58- eqfield
59- nefield
60- gtfield
61- gtefield
62- ltfield
63- ltefield
64- eqcsfield
65- necsfield
66- gtcsfield
67- gtecsfield
68- ltcsfield
69- ltecsfield
70
71If, however, some custom cross-field validation is required, it can be done
72using a custom validation.
73
74Why not just have cross-fields validation tags (i.e. only eqcsfield and not
75eqfield)?
76
77The reason is efficiency. If you want to check a field within the same struct
78"eqfield" only has to find the field on the same struct (1 level). But, if we
79used "eqcsfield" it could be multiple levels down. Example:
80
81type Inner struct {
82StartDate time.Time
83}
84
85type Outer struct {
86InnerStructField *Inner
87CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"`
88}
89
90now := time.Now()
91
92inner := &Inner{
93StartDate: now,
94}
95
96outer := &Outer{
97InnerStructField: inner,
98CreatedAt: now,
99}
100
101errs := validate.Struct(outer)
102
103// NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
104// into the function
105// when calling validate.VarWithValue(val, field, tag) val will be
106// whatever you pass, struct, field...
107// when calling validate.Field(field, tag) val will be nil
108
109# Multiple Validators
110
111Multiple validators on a field will process in the order defined. Example:
112
113type Test struct {
114Field `validate:"max=10,min=1"`
115}
116
117// max will be checked then min
118
119Bad Validator definitions are not handled by the library. Example:
120
121type Test struct {
122Field `validate:"min=10,max=0"`
123}
124
125// this definition of min max will never succeed
126
127# Using Validator Tags
128
129Baked In Cross-Field validation only compares fields on the same struct.
130If Cross-Field + Cross-Struct validation is needed you should implement your
131own custom validator.
132
133Comma (",") is the default separator of validation tags. If you wish to
134have a comma included within the parameter (i.e. excludesall=,) you will need to
135use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
136so the above will become excludesall=0x2C.
137
138type Test struct {
139Field `validate:"excludesall=,"` // BAD! Do not include a comma.
140Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
141}
142
143Pipe ("|") is the 'or' validation tags deparator. If you wish to
144have a pipe included within the parameter i.e. excludesall=| you will need to
145use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
146so the above will become excludesall=0x7C
147
148type Test struct {
149Field `validate:"excludesall=|"` // BAD! Do not include a pipe!
150Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
151}
152
153# Baked In Validators and Tags
154
155Here is a list of the current built in validators:
156
157# Skip Field
158
159Tells the validation to skip this struct field; this is particularly
160handy in ignoring embedded structs from being validated. (Usage: -)
161
162Usage: -
163
164# Or Operator
165
166This is the 'or' operator allowing multiple validators to be used and
167accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba
168colors to be accepted. This can also be combined with 'and' for example
169( Usage: omitempty,rgb|rgba)
170
171Usage: |
172
173# StructOnly
174
175When a field that is a nested struct is encountered, and contains this flag
176any validation on the nested struct will be run, but none of the nested
177struct fields will be validated. This is useful if inside of your program
178you know the struct will be valid, but need to verify it has been assigned.
179NOTE: only "required" and "omitempty" can be used on a struct itself.
180
181Usage: structonly
182
183# NoStructLevel
184
185Same as structonly tag except that any struct level validations will not run.
186
187Usage: nostructlevel
188
189# Omit Empty
190
191Allows conditional validation, for example if a field is not set with
192a value (Determined by the "required" validator) then other validation
193such as min or max won't run, but if a value is set validation will run.
194
195Usage: omitempty
196
197# Omit Nil
198
199Allows to skip the validation if the value is nil (same as omitempty, but
200only for the nil-values).
201
202Usage: omitnil
203
204# Dive
205
206This tells the validator to dive into a slice, array or map and validate that
207level of the slice, array or map with the validation tags that follow.
208Multidimensional nesting is also supported, each level you wish to dive will
209require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
210the Keys & EndKeys section just below.
211
212Usage: dive
213
214Example #1
215
216[][]string with validation tag "gt=0,dive,len=1,dive,required"
217// gt=0 will be applied to []
218// len=1 will be applied to []string
219// required will be applied to string
220
221Example #2
222
223[][]string with validation tag "gt=0,dive,dive,required"
224// gt=0 will be applied to []
225// []string will be spared validation
226// required will be applied to string
227
228Keys & EndKeys
229
230These are to be used together directly after the dive tag and tells the validator
231that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
232values; think of it like the 'dive' tag, but for map keys instead of values.
233Multidimensional nesting is also supported, each level you wish to validate will
234require another 'keys' and 'endkeys' tag. These tags are only valid for maps.
235
236Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
237
238Example #1
239
240map[string]string with validation tag "gt=0,dive,keys,eq=1|eq=2,endkeys,required"
241// gt=0 will be applied to the map itself
242// eq=1|eq=2 will be applied to the map keys
243// required will be applied to map values
244
245Example #2
246
247map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
248// gt=0 will be applied to the map itself
249// eq=1|eq=2 will be applied to each array element in the map keys
250// required will be applied to map values
251
252# Required
253
254This validates that the value is not the data types default zero value.
255For numbers ensures value is not zero. For strings ensures value is
256not "". For slices, maps, pointers, interfaces, channels and functions
257ensures the value is not nil. For structs ensures value is not the zero value when using WithRequiredStructEnabled.
258
259Usage: required
260
261# Required If
262
263The field under validation must be present and not empty only if all
264the other specified fields are equal to the value following the specified
265field. For strings ensures value is not "". For slices, maps, pointers,
266interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
267
268Usage: required_if
269
270Examples:
271
272// require the field if the Field1 is equal to the parameter given:
273Usage: required_if=Field1 foobar
274
275// require the field if the Field1 and Field2 is equal to the value respectively:
276Usage: required_if=Field1 foo Field2 bar
277
278# Required Unless
279
280The field under validation must be present and not empty unless all
281the other specified fields are equal to the value following the specified
282field. For strings ensures value is not "". For slices, maps, pointers,
283interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
284
285Usage: required_unless
286
287Examples:
288
289// require the field unless the Field1 is equal to the parameter given:
290Usage: required_unless=Field1 foobar
291
292// require the field unless the Field1 and Field2 is equal to the value respectively:
293Usage: required_unless=Field1 foo Field2 bar
294
295# Required With
296
297The field under validation must be present and not empty only if any
298of the other specified fields are present. For strings ensures value is
299not "". For slices, maps, pointers, interfaces, channels and functions
300ensures the value is not nil. For structs ensures value is not the zero value.
301
302Usage: required_with
303
304Examples:
305
306// require the field if the Field1 is present:
307Usage: required_with=Field1
308
309// require the field if the Field1 or Field2 is present:
310Usage: required_with=Field1 Field2
311
312# Required With All
313
314The field under validation must be present and not empty only if all
315of the other specified fields are present. For strings ensures value is
316not "". For slices, maps, pointers, interfaces, channels and functions
317ensures the value is not nil. For structs ensures value is not the zero value.
318
319Usage: required_with_all
320
321Example:
322
323// require the field if the Field1 and Field2 is present:
324Usage: required_with_all=Field1 Field2
325
326# Required Without
327
328The field under validation must be present and not empty only when any
329of the other specified fields are not present. For strings ensures value is
330not "". For slices, maps, pointers, interfaces, channels and functions
331ensures the value is not nil. For structs ensures value is not the zero value.
332
333Usage: required_without
334
335Examples:
336
337// require the field if the Field1 is not present:
338Usage: required_without=Field1
339
340// require the field if the Field1 or Field2 is not present:
341Usage: required_without=Field1 Field2
342
343# Required Without All
344
345The field under validation must be present and not empty only when all
346of the other specified fields are not present. For strings ensures value is
347not "". For slices, maps, pointers, interfaces, channels and functions
348ensures the value is not nil. For structs ensures value is not the zero value.
349
350Usage: required_without_all
351
352Example:
353
354// require the field if the Field1 and Field2 is not present:
355Usage: required_without_all=Field1 Field2
356
357# Excluded If
358
359The field under validation must not be present or not empty only if all
360the other specified fields are equal to the value following the specified
361field. For strings ensures value is not "". For slices, maps, pointers,
362interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
363
364Usage: excluded_if
365
366Examples:
367
368// exclude the field if the Field1 is equal to the parameter given:
369Usage: excluded_if=Field1 foobar
370
371// exclude the field if the Field1 and Field2 is equal to the value respectively:
372Usage: excluded_if=Field1 foo Field2 bar
373
374# Excluded Unless
375
376The field under validation must not be present or empty unless all
377the other specified fields are equal to the value following the specified
378field. For strings ensures value is not "". For slices, maps, pointers,
379interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
380
381Usage: excluded_unless
382
383Examples:
384
385// exclude the field unless the Field1 is equal to the parameter given:
386Usage: excluded_unless=Field1 foobar
387
388// exclude the field unless the Field1 and Field2 is equal to the value respectively:
389Usage: excluded_unless=Field1 foo Field2 bar
390
391# Is Default
392
393This validates that the value is the default value and is almost the
394opposite of required.
395
396Usage: isdefault
397
398# Length
399
400For numbers, length will ensure that the value is
401equal to the parameter given. For strings, it checks that
402the string length is exactly that number of characters. For slices,
403arrays, and maps, validates the number of items.
404
405Example #1
406
407Usage: len=10
408
409Example #2 (time.Duration)
410
411For time.Duration, len will ensure that the value is equal to the duration given
412in the parameter.
413
414Usage: len=1h30m
415
416# Maximum
417
418For numbers, max will ensure that the value is
419less than or equal to the parameter given. For strings, it checks
420that the string length is at most that number of characters. For
421slices, arrays, and maps, validates the number of items.
422
423Example #1
424
425Usage: max=10
426
427Example #2 (time.Duration)
428
429For time.Duration, max will ensure that the value is less than or equal to the
430duration given in the parameter.
431
432Usage: max=1h30m
433
434# Minimum
435
436For numbers, min will ensure that the value is
437greater or equal to the parameter given. For strings, it checks that
438the string length is at least that number of characters. For slices,
439arrays, and maps, validates the number of items.
440
441Example #1
442
443Usage: min=10
444
445Example #2 (time.Duration)
446
447For time.Duration, min will ensure that the value is greater than or equal to
448the duration given in the parameter.
449
450Usage: min=1h30m
451
452# Equals
453
454For strings & numbers, eq will ensure that the value is
455equal to the parameter given. For slices, arrays, and maps,
456validates the number of items.
457
458Example #1
459
460Usage: eq=10
461
462Example #2 (time.Duration)
463
464For time.Duration, eq will ensure that the value is equal to the duration given
465in the parameter.
466
467Usage: eq=1h30m
468
469# Not Equal
470
471For strings & numbers, ne will ensure that the value is not
472equal to the parameter given. For slices, arrays, and maps,
473validates the number of items.
474
475Example #1
476
477Usage: ne=10
478
479Example #2 (time.Duration)
480
481For time.Duration, ne will ensure that the value is not equal to the duration
482given in the parameter.
483
484Usage: ne=1h30m
485
486# One Of
487
488For strings, ints, and uints, oneof will ensure that the value
489is one of the values in the parameter. The parameter should be
490a list of values separated by whitespace. Values may be
491strings or numbers. To match strings with spaces in them, include
492the target string between single quotes.
493
494Usage: oneof=red green
495oneof='red green' 'blue yellow'
496oneof=5 7 9
497
498# Greater Than
499
500For numbers, this will ensure that the value is greater than the
501parameter given. For strings, it checks that the string length
502is greater than that number of characters. For slices, arrays
503and maps it validates the number of items.
504
505Example #1
506
507Usage: gt=10
508
509Example #2 (time.Time)
510
511For time.Time ensures the time value is greater than time.Now.UTC().
512
513Usage: gt
514
515Example #3 (time.Duration)
516
517For time.Duration, gt will ensure that the value is greater than the duration
518given in the parameter.
519
520Usage: gt=1h30m
521
522# Greater Than or Equal
523
524Same as 'min' above. Kept both to make terminology with 'len' easier.
525
526Example #1
527
528Usage: gte=10
529
530Example #2 (time.Time)
531
532For time.Time ensures the time value is greater than or equal to time.Now.UTC().
533
534Usage: gte
535
536Example #3 (time.Duration)
537
538For time.Duration, gte will ensure that the value is greater than or equal to
539the duration given in the parameter.
540
541Usage: gte=1h30m
542
543# Less Than
544
545For numbers, this will ensure that the value is less than the parameter given.
546For strings, it checks that the string length is less than that number of
547characters. For slices, arrays, and maps it validates the number of items.
548
549Example #1
550
551Usage: lt=10
552
553Example #2 (time.Time)
554
555For time.Time ensures the time value is less than time.Now.UTC().
556
557Usage: lt
558
559Example #3 (time.Duration)
560
561For time.Duration, lt will ensure that the value is less than the duration given
562in the parameter.
563
564Usage: lt=1h30m
565
566# Less Than or Equal
567
568Same as 'max' above. Kept both to make terminology with 'len' easier.
569
570Example #1
571
572Usage: lte=10
573
574Example #2 (time.Time)
575
576For time.Time ensures the time value is less than or equal to time.Now.UTC().
577
578Usage: lte
579
580Example #3 (time.Duration)
581
582For time.Duration, lte will ensure that the value is less than or equal to the
583duration given in the parameter.
584
585Usage: lte=1h30m
586
587# Field Equals Another Field
588
589This will validate the field value against another fields value either within
590a struct or passed in field.
591
592Example #1:
593
594// Validation on Password field using:
595Usage: eqfield=ConfirmPassword
596
597Example #2:
598
599// Validating by field:
600validate.VarWithValue(password, confirmpassword, "eqfield")
601
602Field Equals Another Field (relative)
603
604This does the same as eqfield except that it validates the field provided relative
605to the top level struct.
606
607Usage: eqcsfield=InnerStructField.Field)
608
609# Field Does Not Equal Another Field
610
611This will validate the field value against another fields value either within
612a struct or passed in field.
613
614Examples:
615
616// Confirm two colors are not the same:
617//
618// Validation on Color field:
619Usage: nefield=Color2
620
621// Validating by field:
622validate.VarWithValue(color1, color2, "nefield")
623
624Field Does Not Equal Another Field (relative)
625
626This does the same as nefield except that it validates the field provided
627relative to the top level struct.
628
629Usage: necsfield=InnerStructField.Field
630
631# Field Greater Than Another Field
632
633Only valid for Numbers, time.Duration and time.Time types, this will validate
634the field value against another fields value either within a struct or passed in
635field. usage examples are for validation of a Start and End date:
636
637Example #1:
638
639// Validation on End field using:
640validate.Struct Usage(gtfield=Start)
641
642Example #2:
643
644// Validating by field:
645validate.VarWithValue(start, end, "gtfield")
646
647# Field Greater Than Another Relative Field
648
649This does the same as gtfield except that it validates the field provided
650relative to the top level struct.
651
652Usage: gtcsfield=InnerStructField.Field
653
654# Field Greater Than or Equal To Another Field
655
656Only valid for Numbers, time.Duration and time.Time types, this will validate
657the field value against another fields value either within a struct or passed in
658field. usage examples are for validation of a Start and End date:
659
660Example #1:
661
662// Validation on End field using:
663validate.Struct Usage(gtefield=Start)
664
665Example #2:
666
667// Validating by field:
668validate.VarWithValue(start, end, "gtefield")
669
670# Field Greater Than or Equal To Another Relative Field
671
672This does the same as gtefield except that it validates the field provided relative
673to the top level struct.
674
675Usage: gtecsfield=InnerStructField.Field
676
677# Less Than Another Field
678
679Only valid for Numbers, time.Duration and time.Time types, this will validate
680the field value against another fields value either within a struct or passed in
681field. usage examples are for validation of a Start and End date:
682
683Example #1:
684
685// Validation on End field using:
686validate.Struct Usage(ltfield=Start)
687
688Example #2:
689
690// Validating by field:
691validate.VarWithValue(start, end, "ltfield")
692
693# Less Than Another Relative Field
694
695This does the same as ltfield except that it validates the field provided relative
696to the top level struct.
697
698Usage: ltcsfield=InnerStructField.Field
699
700# Less Than or Equal To Another Field
701
702Only valid for Numbers, time.Duration and time.Time types, this will validate
703the field value against another fields value either within a struct or passed in
704field. usage examples are for validation of a Start and End date:
705
706Example #1:
707
708// Validation on End field using:
709validate.Struct Usage(ltefield=Start)
710
711Example #2:
712
713// Validating by field:
714validate.VarWithValue(start, end, "ltefield")
715
716# Less Than or Equal To Another Relative Field
717
718This does the same as ltefield except that it validates the field provided relative
719to the top level struct.
720
721Usage: ltecsfield=InnerStructField.Field
722
723# Field Contains Another Field
724
725This does the same as contains except for struct fields. It should only be used
726with string types. See the behavior of reflect.Value.String() for behavior on
727other types.
728
729Usage: containsfield=InnerStructField.Field
730
731# Field Excludes Another Field
732
733This does the same as excludes except for struct fields. It should only be used
734with string types. See the behavior of reflect.Value.String() for behavior on
735other types.
736
737Usage: excludesfield=InnerStructField.Field
738
739# Unique
740
741For arrays & slices, unique will ensure that there are no duplicates.
742For maps, unique will ensure that there are no duplicate values.
743For slices of struct, unique will ensure that there are no duplicate values
744in a field of the struct specified via a parameter.
745
746// For arrays, slices, and maps:
747Usage: unique
748
749// For slices of struct:
750Usage: unique=field
751
752# Alpha Only
753
754This validates that a string value contains ASCII alpha characters only
755
756Usage: alpha
757
758# Alphanumeric
759
760This validates that a string value contains ASCII alphanumeric characters only
761
762Usage: alphanum
763
764# Alpha Unicode
765
766This validates that a string value contains unicode alpha characters only
767
768Usage: alphaunicode
769
770# Alphanumeric Unicode
771
772This validates that a string value contains unicode alphanumeric characters only
773
774Usage: alphanumunicode
775
776# Boolean
777
778This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
779
780Usage: boolean
781
782# Number
783
784This validates that a string value contains number values only.
785For integers or float it returns true.
786
787Usage: number
788
789# Numeric
790
791This validates that a string value contains a basic numeric value.
792basic excludes exponents etc...
793for integers or float it returns true.
794
795Usage: numeric
796
797# Hexadecimal String
798
799This validates that a string value contains a valid hexadecimal.
800
801Usage: hexadecimal
802
803# Hexcolor String
804
805This validates that a string value contains a valid hex color including
806hashtag (#)
807
808Usage: hexcolor
809
810# Lowercase String
811
812This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.
813
814Usage: lowercase
815
816# Uppercase String
817
818This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.
819
820Usage: uppercase
821
822# RGB String
823
824This validates that a string value contains a valid rgb color
825
826Usage: rgb
827
828# RGBA String
829
830This validates that a string value contains a valid rgba color
831
832Usage: rgba
833
834# HSL String
835
836This validates that a string value contains a valid hsl color
837
838Usage: hsl
839
840# HSLA String
841
842This validates that a string value contains a valid hsla color
843
844Usage: hsla
845
846# E.164 Phone Number String
847
848This validates that a string value contains a valid E.164 Phone number
849https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)
850
851Usage: e164
852
853# E-mail String
854
855This validates that a string value contains a valid email
856This may not conform to all possibilities of any rfc standard, but neither
857does any email provider accept all possibilities.
858
859Usage: email
860
861# JSON String
862
863This validates that a string value is valid JSON
864
865Usage: json
866
867# JWT String
868
869This validates that a string value is a valid JWT
870
871Usage: jwt
872
873# File
874
875This validates that a string value contains a valid file path and that
876the file exists on the machine.
877This is done using os.Stat, which is a platform independent function.
878
879Usage: file
880
881# Image path
882
883This validates that a string value contains a valid file path and that
884the file exists on the machine and is an image.
885This is done using os.Stat and github.com/gabriel-vasile/mimetype
886
887Usage: image
888
889# File Path
890
891This validates that a string value contains a valid file path but does not
892validate the existence of that file.
893This is done using os.Stat, which is a platform independent function.
894
895Usage: filepath
896
897# URL String
898
899This validates that a string value contains a valid url
900This will accept any url the golang request uri accepts but must contain
901a schema for example http:// or rtmp://
902
903Usage: url
904
905# URI String
906
907This validates that a string value contains a valid uri
908This will accept any uri the golang request uri accepts
909
910Usage: uri
911
912# Urn RFC 2141 String
913
914This validataes that a string value contains a valid URN
915according to the RFC 2141 spec.
916
917Usage: urn_rfc2141
918
919# Base64 String
920
921This validates that a string value contains a valid base64 value.
922Although an empty string is valid base64 this will report an empty string
923as an error, if you wish to accept an empty string as valid you can use
924this with the omitempty tag.
925
926Usage: base64
927
928# Base64URL String
929
930This validates that a string value contains a valid base64 URL safe value
931according the RFC4648 spec.
932Although an empty string is a valid base64 URL safe value, this will report
933an empty string as an error, if you wish to accept an empty string as valid
934you can use this with the omitempty tag.
935
936Usage: base64url
937
938# Base64RawURL String
939
940This validates that a string value contains a valid base64 URL safe value,
941but without = padding, according the RFC4648 spec, section 3.2.
942Although an empty string is a valid base64 URL safe value, this will report
943an empty string as an error, if you wish to accept an empty string as valid
944you can use this with the omitempty tag.
945
946Usage: base64url
947
948# Bitcoin Address
949
950This validates that a string value contains a valid bitcoin address.
951The format of the string is checked to ensure it matches one of the three formats
952P2PKH, P2SH and performs checksum validation.
953
954Usage: btc_addr
955
956Bitcoin Bech32 Address (segwit)
957
958This validates that a string value contains a valid bitcoin Bech32 address as defined
959by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
960Special thanks to Pieter Wuille for providng reference implementations.
961
962Usage: btc_addr_bech32
963
964# Ethereum Address
965
966This validates that a string value contains a valid ethereum address.
967The format of the string is checked to ensure it matches the standard Ethereum address format.
968
969Usage: eth_addr
970
971# Contains
972
973This validates that a string value contains the substring value.
974
975Usage: contains=@
976
977# Contains Any
978
979This validates that a string value contains any Unicode code points
980in the substring value.
981
982Usage: containsany=!@#?
983
984# Contains Rune
985
986This validates that a string value contains the supplied rune value.
987
988Usage: containsrune=@
989
990# Excludes
991
992This validates that a string value does not contain the substring value.
993
994Usage: excludes=@
995
996# Excludes All
997
998This validates that a string value does not contain any Unicode code
999points in the substring value.
1000
1001Usage: excludesall=!@#?
1002
1003# Excludes Rune
1004
1005This validates that a string value does not contain the supplied rune value.
1006
1007Usage: excludesrune=@
1008
1009# Starts With
1010
1011This validates that a string value starts with the supplied string value
1012
1013Usage: startswith=hello
1014
1015# Ends With
1016
1017This validates that a string value ends with the supplied string value
1018
1019Usage: endswith=goodbye
1020
1021# Does Not Start With
1022
1023This validates that a string value does not start with the supplied string value
1024
1025Usage: startsnotwith=hello
1026
1027# Does Not End With
1028
1029This validates that a string value does not end with the supplied string value
1030
1031Usage: endsnotwith=goodbye
1032
1033# International Standard Book Number
1034
1035This validates that a string value contains a valid isbn10 or isbn13 value.
1036
1037Usage: isbn
1038
1039# International Standard Book Number 10
1040
1041This validates that a string value contains a valid isbn10 value.
1042
1043Usage: isbn10
1044
1045# International Standard Book Number 13
1046
1047This validates that a string value contains a valid isbn13 value.
1048
1049Usage: isbn13
1050
1051# Universally Unique Identifier UUID
1052
1053This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
1054
1055Usage: uuid
1056
1057# Universally Unique Identifier UUID v3
1058
1059This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
1060
1061Usage: uuid3
1062
1063# Universally Unique Identifier UUID v4
1064
1065This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
1066
1067Usage: uuid4
1068
1069# Universally Unique Identifier UUID v5
1070
1071This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
1072
1073Usage: uuid5
1074
1075# Universally Unique Lexicographically Sortable Identifier ULID
1076
1077This validates that a string value contains a valid ULID value.
1078
1079Usage: ulid
1080
1081# ASCII
1082
1083This validates that a string value contains only ASCII characters.
1084NOTE: if the string is blank, this validates as true.
1085
1086Usage: ascii
1087
1088# Printable ASCII
1089
1090This validates that a string value contains only printable ASCII characters.
1091NOTE: if the string is blank, this validates as true.
1092
1093Usage: printascii
1094
1095# Multi-Byte Characters
1096
1097This validates that a string value contains one or more multibyte characters.
1098NOTE: if the string is blank, this validates as true.
1099
1100Usage: multibyte
1101
1102# Data URL
1103
1104This validates that a string value contains a valid DataURI.
1105NOTE: this will also validate that the data portion is valid base64
1106
1107Usage: datauri
1108
1109# Latitude
1110
1111This validates that a string value contains a valid latitude.
1112
1113Usage: latitude
1114
1115# Longitude
1116
1117This validates that a string value contains a valid longitude.
1118
1119Usage: longitude
1120
1121# Social Security Number SSN
1122
1123This validates that a string value contains a valid U.S. Social Security Number.
1124
1125Usage: ssn
1126
1127# Internet Protocol Address IP
1128
1129This validates that a string value contains a valid IP Address.
1130
1131Usage: ip
1132
1133# Internet Protocol Address IPv4
1134
1135This validates that a string value contains a valid v4 IP Address.
1136
1137Usage: ipv4
1138
1139# Internet Protocol Address IPv6
1140
1141This validates that a string value contains a valid v6 IP Address.
1142
1143Usage: ipv6
1144
1145# Classless Inter-Domain Routing CIDR
1146
1147This validates that a string value contains a valid CIDR Address.
1148
1149Usage: cidr
1150
1151# Classless Inter-Domain Routing CIDRv4
1152
1153This validates that a string value contains a valid v4 CIDR Address.
1154
1155Usage: cidrv4
1156
1157# Classless Inter-Domain Routing CIDRv6
1158
1159This validates that a string value contains a valid v6 CIDR Address.
1160
1161Usage: cidrv6
1162
1163# Transmission Control Protocol Address TCP
1164
1165This validates that a string value contains a valid resolvable TCP Address.
1166
1167Usage: tcp_addr
1168
1169# Transmission Control Protocol Address TCPv4
1170
1171This validates that a string value contains a valid resolvable v4 TCP Address.
1172
1173Usage: tcp4_addr
1174
1175# Transmission Control Protocol Address TCPv6
1176
1177This validates that a string value contains a valid resolvable v6 TCP Address.
1178
1179Usage: tcp6_addr
1180
1181# User Datagram Protocol Address UDP
1182
1183This validates that a string value contains a valid resolvable UDP Address.
1184
1185Usage: udp_addr
1186
1187# User Datagram Protocol Address UDPv4
1188
1189This validates that a string value contains a valid resolvable v4 UDP Address.
1190
1191Usage: udp4_addr
1192
1193# User Datagram Protocol Address UDPv6
1194
1195This validates that a string value contains a valid resolvable v6 UDP Address.
1196
1197Usage: udp6_addr
1198
1199# Internet Protocol Address IP
1200
1201This validates that a string value contains a valid resolvable IP Address.
1202
1203Usage: ip_addr
1204
1205# Internet Protocol Address IPv4
1206
1207This validates that a string value contains a valid resolvable v4 IP Address.
1208
1209Usage: ip4_addr
1210
1211# Internet Protocol Address IPv6
1212
1213This validates that a string value contains a valid resolvable v6 IP Address.
1214
1215Usage: ip6_addr
1216
1217# Unix domain socket end point Address
1218
1219This validates that a string value contains a valid Unix Address.
1220
1221Usage: unix_addr
1222
1223# Media Access Control Address MAC
1224
1225This validates that a string value contains a valid MAC Address.
1226
1227Usage: mac
1228
1229Note: See Go's ParseMAC for accepted formats and types:
1230
1231http://golang.org/src/net/mac.go?s=866:918#L29
1232
1233# Hostname RFC 952
1234
1235This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
1236
1237Usage: hostname
1238
1239# Hostname RFC 1123
1240
1241This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
1242
1243Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
1244
1245Full Qualified Domain Name (FQDN)
1246
1247This validates that a string value contains a valid FQDN.
1248
1249Usage: fqdn
1250
1251# HTML Tags
1252
1253This validates that a string value appears to be an HTML element tag
1254including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
1255
1256Usage: html
1257
1258# HTML Encoded
1259
1260This validates that a string value is a proper character reference in decimal
1261or hexadecimal format
1262
1263Usage: html_encoded
1264
1265# URL Encoded
1266
1267This validates that a string value is percent-encoded (URL encoded) according
1268to https://tools.ietf.org/html/rfc3986#section-2.1
1269
1270Usage: url_encoded
1271
1272# Directory
1273
1274This validates that a string value contains a valid directory and that
1275it exists on the machine.
1276This is done using os.Stat, which is a platform independent function.
1277
1278Usage: dir
1279
1280# Directory Path
1281
1282This validates that a string value contains a valid directory but does
1283not validate the existence of that directory.
1284This is done using os.Stat, which is a platform independent function.
1285It is safest to suffix the string with os.PathSeparator if the directory
1286may not exist at the time of validation.
1287
1288Usage: dirpath
1289
1290# HostPort
1291
1292This validates that a string value contains a valid DNS hostname and port that
1293can be used to valiate fields typically passed to sockets and connections.
1294
1295Usage: hostname_port
1296
1297# Datetime
1298
1299This validates that a string value is a valid datetime based on the supplied datetime format.
1300Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
1301
1302Usage: datetime=2006-01-02
1303
1304# Iso3166-1 alpha-2
1305
1306This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
1307see: https://www.iso.org/iso-3166-country-codes.html
1308
1309Usage: iso3166_1_alpha2
1310
1311# Iso3166-1 alpha-3
1312
1313This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
1314see: https://www.iso.org/iso-3166-country-codes.html
1315
1316Usage: iso3166_1_alpha3
1317
1318# Iso3166-1 alpha-numeric
1319
1320This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
1321see: https://www.iso.org/iso-3166-country-codes.html
1322
1323Usage: iso3166_1_alpha3
1324
1325# BCP 47 Language Tag
1326
1327This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
1328More information on https://pkg.go.dev/golang.org/x/text/language
1329
1330Usage: bcp47_language_tag
1331
1332BIC (SWIFT code)
1333
1334This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
1335More information on https://www.iso.org/standard/60390.html
1336
1337Usage: bic
1338
1339# RFC 1035 label
1340
1341This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
1342More information on https://datatracker.ietf.org/doc/html/rfc1035
1343
1344Usage: dns_rfc1035_label
1345
1346# TimeZone
1347
1348This validates that a string value is a valid time zone based on the time zone database present on the system.
1349Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
1350More information on https://golang.org/pkg/time/#LoadLocation
1351
1352Usage: timezone
1353
1354# Semantic Version
1355
1356This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0.
1357More information on https://semver.org/
1358
1359Usage: semver
1360
1361# CVE Identifier
1362
1363This validates that a string value is a valid cve id, defined in cve mitre.
1364More information on https://cve.mitre.org/
1365
1366Usage: cve
1367
1368# Credit Card
1369
1370This validates that a string value contains a valid credit card number using Luhn algorithm.
1371
1372Usage: credit_card
1373
1374# Luhn Checksum
1375
1376Usage: luhn_checksum
1377
1378This validates that a string or (u)int value contains a valid checksum using the Luhn algorithm.
1379
1380# MongoDb ObjectID
1381
1382This validates that a string is a valid 24 character hexadecimal string.
1383
1384Usage: mongodb
1385
1386# Cron
1387
1388This validates that a string value contains a valid cron expression.
1389
1390Usage: cron
1391
1392# SpiceDb ObjectID/Permission/Object Type
1393
1394This validates that a string is valid for use with SpiceDb for the indicated purpose. If no purpose is given, a purpose of 'id' is assumed.
1395
1396Usage: spicedb=id|permission|type
1397
1398# Alias Validators and Tags
1399
1400Alias Validators and Tags
1401NOTE: When returning an error, the tag returned in "FieldError" will be
1402the alias tag unless the dive tag is part of the alias. Everything after the
1403dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
1404case will be the actual tag within the alias that failed.
1405
1406Here is a list of the current built in alias tags:
1407
1408"iscolor"
1409alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
1410"country_code"
1411alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
1412
1413Validator notes:
1414
1415regex
1416a regex validator won't be added because commas and = signs can be part
1417of a regex which conflict with the validation definitions. Although
1418workarounds can be made, they take away from using pure regex's.
1419Furthermore it's quick and dirty but the regex's become harder to
1420maintain and are not reusable, so it's as much a programming philosophy
1421as anything.
1422
1423In place of this new validator functions should be created; a regex can
1424be used within the validator function and even be precompiled for better
1425efficiency within regexes.go.
1426
1427And the best reason, you can submit a pull request and we can keep on
1428adding to the validation library of this package!
1429
1430# Non standard validators
1431
1432A collection of validation rules that are frequently needed but are more
1433complex than the ones found in the baked in validators.
1434A non standard validator must be registered manually like you would
1435with your own custom validation functions.
1436
1437Example of registration and use:
1438
1439type Test struct {
1440TestField string `validate:"yourtag"`
1441}
1442
1443t := &Test{
1444TestField: "Test"
1445}
1446
1447validate := validator.New()
1448validate.RegisterValidation("yourtag", validators.NotBlank)
1449
1450Here is a list of the current non standard validators:
1451
1452NotBlank
1453This validates that the value is not blank or with length zero.
1454For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
1455ensures they don't have zero length. For others, a non empty value is required.
1456
1457Usage: notblank
1458
1459# Panics
1460
1461This package panics when bad input is provided, this is by design, bad code like
1462that should not make it to production.
1463
1464type Test struct {
1465TestField string `validate:"nonexistantfunction=1"`
1466}
1467
1468t := &Test{
1469TestField: "Test"
1470}
1471
1472validate.Struct(t) // this will panic
1473*/
1474package validator
1475