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