...

Source file src/github.com/go-playground/validator/v10/doc.go

Documentation: github.com/go-playground/validator/v10

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

View as plain text