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 Why not a better error message?
9 Because this library intends for you to handle your own error messages.
11 Why should I handle my own errors?
12 Many reasons. We built an internationalized application and needed to know the
13 field, and what validation failed so we could provide a localized error.
15 if fieldErr.Field == "Name" {
16 switch fieldErr.ErrorTag
18 return "Translated string based on field + error"
20 return "Translated string based on field"
24 Validation Functions Return Type error
26 Doing things this way is actually the way the standard library does, see the
27 file.Open method here:
29 https://golang.org/pkg/os/#Open.
31 The authors return type "error" to avoid the issue discussed in the following,
32 where err is always != nil:
34 http://stackoverflow.com/a/29138676/3158232
35 https://github.com/go-playground/validator/issues/134
37 Validator only returns nil or ValidationErrors as type error; so, in your code
38 all you need to do is check if the error returned is not nil, and if it's not
39 type cast it to type ValidationErrors like so err.(validator.ValidationErrors).
43 Custom functions can be added. Example:
46 func customFunc(v *Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
55 validate.RegisterValidation("custom tag name", customFunc)
56 // NOTES: using the same tag name as an existing function
57 // will overwrite the existing one
59 Cross-Field Validation
61 Cross-Field Validation can be done via the following tags:
75 If, however, some custom cross-field validation is required, it can be done
76 using a custom validation.
78 Why not just have cross-fields validation tags (i.e. only eqcsfield and not
81 The reason is efficiency. If you want to check a field within the same struct
82 "eqfield" only has to find the field on the same struct (1 level). But, if we
83 used "eqcsfield" it could be multiple levels down. Example:
90 InnerStructField *Inner
91 CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"`
101 InnerStructField: inner,
105 errs := validate.Struct(outer)
107 // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
109 // when calling validate.FieldWithValue(val, field, tag) val will be
110 // whatever you pass, struct, field...
111 // when calling validate.Field(field, tag) val will be nil
115 Multiple validators on a field will process in the order defined. Example:
118 Field `validate:"max=10,min=1"`
121 // max will be checked then min
123 Bad Validator definitions are not handled by the library. Example:
126 Field `validate:"min=10,max=0"`
129 // this definition of min max will never succeed
133 Baked In Cross-Field validation only compares fields on the same struct.
134 If Cross-Field + Cross-Struct validation is needed you should implement your
135 own custom validator.
137 Comma (",") is the default separator of validation tags. If you wish to
138 have a comma included within the parameter (i.e. excludesall=,) you will need to
139 use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
140 so the above will become excludesall=0x2C.
143 Field `validate:"excludesall=,"` // BAD! Do not include a comma.
144 Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
147 Pipe ("|") is the default separator of validation tags. If you wish to
148 have a pipe included within the parameter i.e. excludesall=| you will need to
149 use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
150 so the above will become excludesall=0x7C
153 Field `validate:"excludesall=|"` // BAD! Do not include a a pipe!
154 Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
158 Baked In Validators and Tags
160 Here is a list of the current built in validators:
165 Tells the validation to skip this struct field; this is particularly
166 handy in ignoring embedded structs from being validated. (Usage: -)
172 This is the 'or' operator allowing multiple validators to be used and
173 accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba
174 colors to be accepted. This can also be combined with 'and' for example
175 ( Usage: omitempty,rgb|rgba)
181 When a field that is a nested struct is encountered, and contains this flag
182 any validation on the nested struct will be run, but none of the nested
183 struct fields will be validated. This is usefull if inside of you program
184 you know the struct will be valid, but need to verify it has been assigned.
185 NOTE: only "required" and "omitempty" can be used on a struct itself.
191 Same as structonly tag except that any struct level validations will not run.
197 Is a special tag without a validation function attached. It is used when a field
198 is a Pointer, Interface or Invalid and you wish to validate that it exists.
199 Example: want to ensure a bool exists if you define the bool as a pointer and
200 use exists it will ensure there is a value; couldn't use required as it would
201 fail when the bool was false. exists will fail is the value is a Pointer, Interface
202 or Invalid and is nil.
208 Allows conditional validation, for example if a field is not set with
209 a value (Determined by the "required" validator) then other validation
210 such as min or max won't run, but if a value is set validation will run.
216 This tells the validator to dive into a slice, array or map and validate that
217 level of the slice, array or map with the validation tags that follow.
218 Multidimensional nesting is also supported, each level you wish to dive will
219 require another dive tag.
225 [][]string with validation tag "gt=0,dive,len=1,dive,required"
226 // gt=0 will be applied to []
227 // len=1 will be applied to []string
228 // required will be applied to string
232 [][]string with validation tag "gt=0,dive,dive,required"
233 // gt=0 will be applied to []
234 // []string will be spared validation
235 // required will be applied to string
239 This validates that the value is not the data types default zero value.
240 For numbers ensures value is not zero. For strings ensures value is
241 not "". For slices, maps, pointers, interfaces, channels and functions
242 ensures the value is not nil.
248 For numbers, max will ensure that the value is
249 equal to the parameter given. For strings, it checks that
250 the string length is exactly that number of characters. For slices,
251 arrays, and maps, validates the number of items.
257 For numbers, max will ensure that the value is
258 less than or equal to the parameter given. For strings, it checks
259 that the string length is at most that number of characters. For
260 slices, arrays, and maps, validates the number of items.
266 For numbers, min will ensure that the value is
267 greater or equal to the parameter given. For strings, it checks that
268 the string length is at least that number of characters. For slices,
269 arrays, and maps, validates the number of items.
275 For strings & numbers, eq will ensure that the value is
276 equal to the parameter given. For slices, arrays, and maps,
277 validates the number of items.
283 For strings & numbers, ne will ensure that the value is not
284 equal to the parameter given. For slices, arrays, and maps,
285 validates the number of items.
291 For numbers, this will ensure that the value is greater than the
292 parameter given. For strings, it checks that the string length
293 is greater than that number of characters. For slices, arrays
294 and maps it validates the number of items.
300 Example #2 (time.Time)
302 For time.Time ensures the time value is greater than time.Now.UTC().
306 Greater Than or Equal
308 Same as 'min' above. Kept both to make terminology with 'len' easier.
315 Example #2 (time.Time)
317 For time.Time ensures the time value is greater than or equal to time.Now.UTC().
323 For numbers, this will ensure that the value is less than the parameter given.
324 For strings, it checks that the string length is less than that number of
325 characters. For slices, arrays, and maps it validates the number of items.
331 Example #2 (time.Time)
332 For time.Time ensures the time value is less than time.Now.UTC().
338 Same as 'max' above. Kept both to make terminology with 'len' easier.
344 Example #2 (time.Time)
346 For time.Time ensures the time value is less than or equal to time.Now.UTC().
350 Field Equals Another Field
352 This will validate the field value against another fields value either within
353 a struct or passed in field.
357 // Validation on Password field using:
358 Usage: eqfield=ConfirmPassword
362 // Validating by field:
363 validate.FieldWithValue(password, confirmpassword, "eqfield")
365 Field Equals Another Field (relative)
367 This does the same as eqfield except that it validates the field provided relative
368 to the top level struct.
370 Usage: eqcsfield=InnerStructField.Field)
372 Field Does Not Equal Another Field
374 This will validate the field value against another fields value either within
375 a struct or passed in field.
379 // Confirm two colors are not the same:
381 // Validation on Color field:
382 Usage: nefield=Color2
384 // Validating by field:
385 validate.FieldWithValue(color1, color2, "nefield")
387 Field Does Not Equal Another Field (relative)
389 This does the same as nefield except that it validates the field provided
390 relative to the top level struct.
392 Usage: necsfield=InnerStructField.Field
394 Field Greater Than Another Field
396 Only valid for Numbers and time.Time types, this will validate the field value
397 against another fields value either within a struct or passed in field.
398 usage examples are for validation of a Start and End date:
402 // Validation on End field using:
403 validate.Struct Usage(gtfield=Start)
407 // Validating by field:
408 validate.FieldWithValue(start, end, "gtfield")
411 Field Greater Than Another Relative Field
413 This does the same as gtfield except that it validates the field provided
414 relative to the top level struct.
416 Usage: gtcsfield=InnerStructField.Field
418 Field Greater Than or Equal To Another Field
420 Only valid for Numbers and time.Time types, this will validate the field value
421 against another fields value either within a struct or passed in field.
422 usage examples are for validation of a Start and End date:
426 // Validation on End field using:
427 validate.Struct Usage(gtefield=Start)
431 // Validating by field:
432 validate.FieldWithValue(start, end, "gtefield")
434 Field Greater Than or Equal To Another Relative Field
436 This does the same as gtefield except that it validates the field provided relative
437 to the top level struct.
439 Usage: gtecsfield=InnerStructField.Field
441 Less Than Another Field
443 Only valid for Numbers and time.Time types, this will validate the field value
444 against another fields value either within a struct or passed in field.
445 usage examples are for validation of a Start and End date:
449 // Validation on End field using:
450 validate.Struct Usage(ltfield=Start)
454 // Validating by field:
455 validate.FieldWithValue(start, end, "ltfield")
457 Less Than Another Relative Field
459 This does the same as ltfield except that it validates the field provided relative
460 to the top level struct.
462 Usage: ltcsfield=InnerStructField.Field
464 Less Than or Equal To Another Field
466 Only valid for Numbers and time.Time types, this will validate the field value
467 against another fields value either within a struct or passed in field.
468 usage examples are for validation of a Start and End date:
472 // Validation on End field using:
473 validate.Struct Usage(ltefield=Start)
477 // Validating by field:
478 validate.FieldWithValue(start, end, "ltefield")
480 Less Than or Equal To Another Relative Field
482 This does the same as ltefield except that it validates the field provided relative
483 to the top level struct.
485 Usage: ltecsfield=InnerStructField.Field
489 This validates that a string value contains alpha characters only
495 This validates that a string value contains alphanumeric characters only
501 This validates that a string value contains a basic numeric value.
502 basic excludes exponents etc...
508 This validates that a string value contains a valid hexadecimal.
514 This validates that a string value contains a valid hex color including
521 This validates that a string value contains a valid rgb color
527 This validates that a string value contains a valid rgba color
533 This validates that a string value contains a valid hsl color
539 This validates that a string value contains a valid hsla color
545 This validates that a string value contains a valid email
546 This may not conform to all possibilities of any rfc standard, but neither
547 does any email provider accept all posibilities.
553 This validates that a string value contains a valid url
554 This will accept any url the golang request uri accepts but must contain
555 a schema for example http:// or rtmp://
561 This validates that a string value contains a valid uri
562 This will accept any uri the golang request uri accepts
568 This validates that a string value contains a valid base64 value.
569 Although an empty string is valid base64 this will report an empty string
570 as an error, if you wish to accept an empty string as valid you can use
571 this with the omitempty tag.
577 This validates that a string value contains the substring value.
583 This validates that a string value contains any Unicode code points
584 in the substring value.
586 Usage: containsany=!@#?
590 This validates that a string value contains the supplied rune value.
592 Usage: containsrune=@
596 This validates that a string value does not contain the substring value.
602 This validates that a string value does not contain any Unicode code
603 points in the substring value.
605 Usage: excludesall=!@#?
609 This validates that a string value does not contain the supplied rune value.
611 Usage: excludesrune=@
613 International Standard Book Number
615 This validates that a string value contains a valid isbn10 or isbn13 value.
619 International Standard Book Number 10
621 This validates that a string value contains a valid isbn10 value.
625 International Standard Book Number 13
627 This validates that a string value contains a valid isbn13 value.
632 Universally Unique Identifier UUID
634 This validates that a string value contains a valid UUID.
638 Universally Unique Identifier UUID v3
640 This validates that a string value contains a valid version 3 UUID.
644 Universally Unique Identifier UUID v4
646 This validates that a string value contains a valid version 4 UUID.
650 Universally Unique Identifier UUID v5
652 This validates that a string value contains a valid version 5 UUID.
658 This validates that a string value contains only ASCII characters.
659 NOTE: if the string is blank, this validates as true.
665 This validates that a string value contains only printable ASCII characters.
666 NOTE: if the string is blank, this validates as true.
670 Multi-Byte Characters
672 This validates that a string value contains one or more multibyte characters.
673 NOTE: if the string is blank, this validates as true.
679 This validates that a string value contains a valid DataURI.
680 NOTE: this will also validate that the data portion is valid base64
686 This validates that a string value contains a valid latitude.
692 This validates that a string value contains a valid longitude.
696 Social Security Number SSN
698 This validates that a string value contains a valid U.S. Social Security Number.
702 Internet Protocol Address IP
704 This validates that a string value contains a valid IP Adress.
708 Internet Protocol Address IPv4
710 This validates that a string value contains a valid v4 IP Adress.
714 Internet Protocol Address IPv6
716 This validates that a string value contains a valid v6 IP Adress.
720 Classless Inter-Domain Routing CIDR
722 This validates that a string value contains a valid CIDR Adress.
726 Classless Inter-Domain Routing CIDRv4
728 This validates that a string value contains a valid v4 CIDR Adress.
732 Classless Inter-Domain Routing CIDRv6
734 This validates that a string value contains a valid v6 CIDR Adress.
738 Transmission Control Protocol Address TCP
740 This validates that a string value contains a valid resolvable TCP Adress.
744 Transmission Control Protocol Address TCPv4
746 This validates that a string value contains a valid resolvable v4 TCP Adress.
750 Transmission Control Protocol Address TCPv6
752 This validates that a string value contains a valid resolvable v6 TCP Adress.
756 User Datagram Protocol Address UDP
758 This validates that a string value contains a valid resolvable UDP Adress.
762 User Datagram Protocol Address UDPv4
764 This validates that a string value contains a valid resolvable v4 UDP Adress.
768 User Datagram Protocol Address UDPv6
770 This validates that a string value contains a valid resolvable v6 UDP Adress.
774 Internet Protocol Address IP
776 This validates that a string value contains a valid resolvable IP Adress.
780 Internet Protocol Address IPv4
782 This validates that a string value contains a valid resolvable v4 IP Adress.
786 Internet Protocol Address IPv6
788 This validates that a string value contains a valid resolvable v6 IP Adress.
792 Unix domain socket end point Address
794 This validates that a string value contains a valid Unix Adress.
798 Media Access Control Address MAC
800 This validates that a string value contains a valid MAC Adress.
804 Note: See Go's ParseMAC for accepted formats and types:
806 http://golang.org/src/net/mac.go?s=866:918#L29
808 Alias Validators and Tags
810 NOTE: When returning an error, the tag returned in "FieldError" will be
811 the alias tag unless the dive tag is part of the alias. Everything after the
812 dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
813 case will be the actual tag within the alias that failed.
815 Here is a list of the current built in alias tags:
818 alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
823 a regex validator won't be added because commas and = signs can be part
824 of a regex which conflict with the validation definitions. Although
825 workarounds can be made, they take away from using pure regex's.
826 Furthermore it's quick and dirty but the regex's become harder to
827 maintain and are not reusable, so it's as much a programming philosiphy
830 In place of this new validator functions should be created; a regex can
831 be used within the validator function and even be precompiled for better
832 efficiency within regexes.go.
834 And the best reason, you can submit a pull request and we can keep on
835 adding to the validation library of this package!
839 This package panics when bad input is provided, this is by design, bad code like
840 that should not make it to production.
843 TestField string `validate:"nonexistantfunction=1"`
850 validate.Struct(t) // this will panic