2 Package validator implements value validations for structs and individual fields
5 It can also handle Cross-Field and Cross-Struct validation for nested structs
6 and has the ability to dive into arrays and maps of any type.
8 see more examples https://github.com/go-playground/validator/tree/v9/_examples
10 Validation Functions Return Type error
12 Doing things this way is actually the way the standard library does, see the
13 file.Open method here:
15 https://golang.org/pkg/os/#Open.
17 The authors return type "error" to avoid the issue discussed in the following,
18 where err is always != nil:
20 http://stackoverflow.com/a/29138676/3158232
21 https://github.com/go-playground/validator/issues/134
23 Validator only InvalidValidationError for bad validation input, nil or
24 ValidationErrors as type error; so, in your code all you need to do is check
25 if the error returned is not nil, and if it's not check if error is
26 InvalidValidationError ( if necessary, most of the time it isn't ) type cast
27 it to type ValidationErrors like so err.(validator.ValidationErrors).
29 Custom Validation Functions
31 Custom Validation functions can be added. Example:
34 func customFunc(fl FieldLevel) bool {
36 if fl.Field().String() == "invalid" {
43 validate.RegisterValidation("custom tag name", customFunc)
44 // NOTES: using the same tag name as an existing function
45 // will overwrite the existing one
47 Cross-Field Validation
49 Cross-Field Validation can be done via the following tags:
63 If, however, some custom cross-field validation is required, it can be done
64 using a custom validation.
66 Why not just have cross-fields validation tags (i.e. only eqcsfield and not
69 The reason is efficiency. If you want to check a field within the same struct
70 "eqfield" only has to find the field on the same struct (1 level). But, if we
71 used "eqcsfield" it could be multiple levels down. Example:
78 InnerStructField *Inner
79 CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"`
89 InnerStructField: inner,
93 errs := validate.Struct(outer)
95 // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
97 // when calling validate.FieldWithValue(val, field, tag) val will be
98 // whatever you pass, struct, field...
99 // when calling validate.Field(field, tag) val will be nil
103 Multiple validators on a field will process in the order defined. Example:
106 Field `validate:"max=10,min=1"`
109 // max will be checked then min
111 Bad Validator definitions are not handled by the library. Example:
114 Field `validate:"min=10,max=0"`
117 // this definition of min max will never succeed
121 Baked In Cross-Field validation only compares fields on the same struct.
122 If Cross-Field + Cross-Struct validation is needed you should implement your
123 own custom validator.
125 Comma (",") is the default separator of validation tags. If you wish to
126 have a comma included within the parameter (i.e. excludesall=,) you will need to
127 use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
128 so the above will become excludesall=0x2C.
131 Field `validate:"excludesall=,"` // BAD! Do not include a comma.
132 Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
135 Pipe ("|") is the default separator of validation tags. If you wish to
136 have a pipe included within the parameter i.e. excludesall=| you will need to
137 use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
138 so the above will become excludesall=0x7C
141 Field `validate:"excludesall=|"` // BAD! Do not include a a pipe!
142 Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
146 Baked In Validators and Tags
148 Here is a list of the current built in validators:
153 Tells the validation to skip this struct field; this is particularly
154 handy in ignoring embedded structs from being validated. (Usage: -)
160 This is the 'or' operator allowing multiple validators to be used and
161 accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba
162 colors to be accepted. This can also be combined with 'and' for example
163 ( Usage: omitempty,rgb|rgba)
169 When a field that is a nested struct is encountered, and contains this flag
170 any validation on the nested struct will be run, but none of the nested
171 struct fields will be validated. This is usefull if inside of you program
172 you know the struct will be valid, but need to verify it has been assigned.
173 NOTE: only "required" and "omitempty" can be used on a struct itself.
179 Same as structonly tag except that any struct level validations will not run.
185 Allows conditional validation, for example if a field is not set with
186 a value (Determined by the "required" validator) then other validation
187 such as min or max won't run, but if a value is set validation will run.
193 This tells the validator to dive into a slice, array or map and validate that
194 level of the slice, array or map with the validation tags that follow.
195 Multidimensional nesting is also supported, each level you wish to dive will
196 require another dive tag.
202 [][]string with validation tag "gt=0,dive,len=1,dive,required"
203 // gt=0 will be applied to []
204 // len=1 will be applied to []string
205 // required will be applied to string
209 [][]string with validation tag "gt=0,dive,dive,required"
210 // gt=0 will be applied to []
211 // []string will be spared validation
212 // required will be applied to string
216 This validates that the value is not the data types default zero value.
217 For numbers ensures value is not zero. For strings ensures value is
218 not "". For slices, maps, pointers, interfaces, channels and functions
219 ensures the value is not nil.
225 This validates that the value is the default value and is almost the
226 opposite of required.
232 For numbers, length will ensure that the value is
233 equal to the parameter given. For strings, it checks that
234 the string length is exactly that number of characters. For slices,
235 arrays, and maps, validates the number of items.
241 For numbers, max will ensure that the value is
242 less than or equal to the parameter given. For strings, it checks
243 that the string length is at most that number of characters. For
244 slices, arrays, and maps, validates the number of items.
250 For numbers, min will ensure that the value is
251 greater or equal to the parameter given. For strings, it checks that
252 the string length is at least that number of characters. For slices,
253 arrays, and maps, validates the number of items.
259 For strings & numbers, eq will ensure that the value is
260 equal to the parameter given. For slices, arrays, and maps,
261 validates the number of items.
267 For strings & numbers, ne will ensure that the value is not
268 equal to the parameter given. For slices, arrays, and maps,
269 validates the number of items.
275 For numbers, this will ensure that the value is greater than the
276 parameter given. For strings, it checks that the string length
277 is greater than that number of characters. For slices, arrays
278 and maps it validates the number of items.
284 Example #2 (time.Time)
286 For time.Time ensures the time value is greater than time.Now.UTC().
290 Greater Than or Equal
292 Same as 'min' above. Kept both to make terminology with 'len' easier.
299 Example #2 (time.Time)
301 For time.Time ensures the time value is greater than or equal to time.Now.UTC().
307 For numbers, this will ensure that the value is less than the parameter given.
308 For strings, it checks that the string length is less than that number of
309 characters. For slices, arrays, and maps it validates the number of items.
315 Example #2 (time.Time)
316 For time.Time ensures the time value is less than time.Now.UTC().
322 Same as 'max' above. Kept both to make terminology with 'len' easier.
328 Example #2 (time.Time)
330 For time.Time ensures the time value is less than or equal to time.Now.UTC().
334 Field Equals Another Field
336 This will validate the field value against another fields value either within
337 a struct or passed in field.
341 // Validation on Password field using:
342 Usage: eqfield=ConfirmPassword
346 // Validating by field:
347 validate.FieldWithValue(password, confirmpassword, "eqfield")
349 Field Equals Another Field (relative)
351 This does the same as eqfield except that it validates the field provided relative
352 to the top level struct.
354 Usage: eqcsfield=InnerStructField.Field)
356 Field Does Not Equal Another Field
358 This will validate the field value against another fields value either within
359 a struct or passed in field.
363 // Confirm two colors are not the same:
365 // Validation on Color field:
366 Usage: nefield=Color2
368 // Validating by field:
369 validate.FieldWithValue(color1, color2, "nefield")
371 Field Does Not Equal Another Field (relative)
373 This does the same as nefield except that it validates the field provided
374 relative to the top level struct.
376 Usage: necsfield=InnerStructField.Field
378 Field Greater Than Another Field
380 Only valid for Numbers and time.Time types, this will validate the field value
381 against another fields value either within a struct or passed in field.
382 usage examples are for validation of a Start and End date:
386 // Validation on End field using:
387 validate.Struct Usage(gtfield=Start)
391 // Validating by field:
392 validate.FieldWithValue(start, end, "gtfield")
395 Field Greater Than Another Relative Field
397 This does the same as gtfield except that it validates the field provided
398 relative to the top level struct.
400 Usage: gtcsfield=InnerStructField.Field
402 Field Greater Than or Equal To Another Field
404 Only valid for Numbers and time.Time types, this will validate the field value
405 against another fields value either within a struct or passed in field.
406 usage examples are for validation of a Start and End date:
410 // Validation on End field using:
411 validate.Struct Usage(gtefield=Start)
415 // Validating by field:
416 validate.FieldWithValue(start, end, "gtefield")
418 Field Greater Than or Equal To Another Relative Field
420 This does the same as gtefield except that it validates the field provided relative
421 to the top level struct.
423 Usage: gtecsfield=InnerStructField.Field
425 Less Than Another Field
427 Only valid for Numbers and time.Time types, this will validate the field value
428 against another fields value either within a struct or passed in field.
429 usage examples are for validation of a Start and End date:
433 // Validation on End field using:
434 validate.Struct Usage(ltfield=Start)
438 // Validating by field:
439 validate.FieldWithValue(start, end, "ltfield")
441 Less Than Another Relative Field
443 This does the same as ltfield except that it validates the field provided relative
444 to the top level struct.
446 Usage: ltcsfield=InnerStructField.Field
448 Less Than or Equal To Another Field
450 Only valid for Numbers and time.Time types, this will validate the field value
451 against another fields value either within a struct or passed in field.
452 usage examples are for validation of a Start and End date:
456 // Validation on End field using:
457 validate.Struct Usage(ltefield=Start)
461 // Validating by field:
462 validate.FieldWithValue(start, end, "ltefield")
464 Less Than or Equal To Another Relative Field
466 This does the same as ltefield except that it validates the field provided relative
467 to the top level struct.
469 Usage: ltecsfield=InnerStructField.Field
473 For arrays & slices, unique will ensure that there are no duplicates.
479 This validates that a string value contains ASCII alpha characters only
485 This validates that a string value contains ASCII alphanumeric characters only
491 This validates that a string value contains unicode alpha characters only
497 This validates that a string value contains unicode alphanumeric characters only
499 Usage: alphanumunicode
503 This validates that a string value contains a basic numeric value.
504 basic excludes exponents etc...
510 This validates that a string value contains a valid hexadecimal.
516 This validates that a string value contains a valid hex color including
523 This validates that a string value contains a valid rgb color
529 This validates that a string value contains a valid rgba color
535 This validates that a string value contains a valid hsl color
541 This validates that a string value contains a valid hsla color
547 This validates that a string value contains a valid email
548 This may not conform to all possibilities of any rfc standard, but neither
549 does any email provider accept all posibilities.
555 This validates that a string value contains a valid url
556 This will accept any url the golang request uri accepts but must contain
557 a schema for example http:// or rtmp://
563 This validates that a string value contains a valid uri
564 This will accept any uri the golang request uri accepts
570 This validates that a string value contains a valid base64 value.
571 Although an empty string is valid base64 this will report an empty string
572 as an error, if you wish to accept an empty string as valid you can use
573 this with the omitempty tag.
579 This validates that a string value contains the substring value.
585 This validates that a string value contains any Unicode code points
586 in the substring value.
588 Usage: containsany=!@#?
592 This validates that a string value contains the supplied rune value.
594 Usage: containsrune=@
598 This validates that a string value does not contain the substring value.
604 This validates that a string value does not contain any Unicode code
605 points in the substring value.
607 Usage: excludesall=!@#?
611 This validates that a string value does not contain the supplied rune value.
613 Usage: excludesrune=@
615 International Standard Book Number
617 This validates that a string value contains a valid isbn10 or isbn13 value.
621 International Standard Book Number 10
623 This validates that a string value contains a valid isbn10 value.
627 International Standard Book Number 13
629 This validates that a string value contains a valid isbn13 value.
634 Universally Unique Identifier UUID
636 This validates that a string value contains a valid UUID.
640 Universally Unique Identifier UUID v3
642 This validates that a string value contains a valid version 3 UUID.
646 Universally Unique Identifier UUID v4
648 This validates that a string value contains a valid version 4 UUID.
652 Universally Unique Identifier UUID v5
654 This validates that a string value contains a valid version 5 UUID.
660 This validates that a string value contains only ASCII characters.
661 NOTE: if the string is blank, this validates as true.
667 This validates that a string value contains only printable ASCII characters.
668 NOTE: if the string is blank, this validates as true.
672 Multi-Byte Characters
674 This validates that a string value contains one or more multibyte characters.
675 NOTE: if the string is blank, this validates as true.
681 This validates that a string value contains a valid DataURI.
682 NOTE: this will also validate that the data portion is valid base64
688 This validates that a string value contains a valid latitude.
694 This validates that a string value contains a valid longitude.
698 Social Security Number SSN
700 This validates that a string value contains a valid U.S. Social Security Number.
704 Internet Protocol Address IP
706 This validates that a string value contains a valid IP Adress.
710 Internet Protocol Address IPv4
712 This validates that a string value contains a valid v4 IP Adress.
716 Internet Protocol Address IPv6
718 This validates that a string value contains a valid v6 IP Adress.
722 Classless Inter-Domain Routing CIDR
724 This validates that a string value contains a valid CIDR Adress.
728 Classless Inter-Domain Routing CIDRv4
730 This validates that a string value contains a valid v4 CIDR Adress.
734 Classless Inter-Domain Routing CIDRv6
736 This validates that a string value contains a valid v6 CIDR Adress.
740 Transmission Control Protocol Address TCP
742 This validates that a string value contains a valid resolvable TCP Adress.
746 Transmission Control Protocol Address TCPv4
748 This validates that a string value contains a valid resolvable v4 TCP Adress.
752 Transmission Control Protocol Address TCPv6
754 This validates that a string value contains a valid resolvable v6 TCP Adress.
758 User Datagram Protocol Address UDP
760 This validates that a string value contains a valid resolvable UDP Adress.
764 User Datagram Protocol Address UDPv4
766 This validates that a string value contains a valid resolvable v4 UDP Adress.
770 User Datagram Protocol Address UDPv6
772 This validates that a string value contains a valid resolvable v6 UDP Adress.
776 Internet Protocol Address IP
778 This validates that a string value contains a valid resolvable IP Adress.
782 Internet Protocol Address IPv4
784 This validates that a string value contains a valid resolvable v4 IP Adress.
788 Internet Protocol Address IPv6
790 This validates that a string value contains a valid resolvable v6 IP Adress.
794 Unix domain socket end point Address
796 This validates that a string value contains a valid Unix Adress.
800 Media Access Control Address MAC
802 This validates that a string value contains a valid MAC Adress.
806 Note: See Go's ParseMAC for accepted formats and types:
808 http://golang.org/src/net/mac.go?s=866:918#L29
812 This validates that a string value is a valid Hostname
816 Full Qualified Domain Name (FQDN)
818 This validates that a string value contains a valid FQDN.
822 Alias Validators and Tags
824 NOTE: When returning an error, the tag returned in "FieldError" will be
825 the alias tag unless the dive tag is part of the alias. Everything after the
826 dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
827 case will be the actual tag within the alias that failed.
829 Here is a list of the current built in alias tags:
832 alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
837 a regex validator won't be added because commas and = signs can be part
838 of a regex which conflict with the validation definitions. Although
839 workarounds can be made, they take away from using pure regex's.
840 Furthermore it's quick and dirty but the regex's become harder to
841 maintain and are not reusable, so it's as much a programming philosiphy
844 In place of this new validator functions should be created; a regex can
845 be used within the validator function and even be precompiled for better
846 efficiency within regexes.go.
848 And the best reason, you can submit a pull request and we can keep on
849 adding to the validation library of this package!
853 This package panics when bad input is provided, this is by design, bad code like
854 that should not make it to production.
857 TestField string `validate:"nonexistantfunction=1"`
864 validate.Struct(t) // this will panic