github.com/tanqiangyes/govalidator@v0.0.5/README.md (about) 1 govalidator 2 =========== 3 [](https://godoc.org/github.com/tanqiangyes/govalidator)[](https://goreportcard.com/report/github.com/tanqiangyes/govalidator)[](#backers) [](#sponsors) 4 5 A package of validators and sanitizers for strings, structs and collections, based on **Go 1.18+ Generics**. Based on [asaskevich/govalidator](https://github.com/asaskevich/govalidator). 6 7 #### Installation 8 Make sure that Go is installed on your computer. 9 Type the following command in your terminal: 10 11 go get github.com/tanqiangyes/govalidator 12 13 or you can get specified release of the package with `gopkg.in`: 14 15 go get gopkg.in/tanqiangyes/govalidator.v10 16 17 After it the package is ready to use. 18 19 20 #### Import package in your project 21 Add following line in your `*.go` file: 22 ```go 23 import "github.com/tanqiangyes/govalidator" 24 ``` 25 If you are unhappy to use long `govalidator`, you can do something like this: 26 ```go 27 import ( 28 valid "github.com/tanqiangyes/govalidator" 29 ) 30 ``` 31 32 #### Activate behavior to require all fields have a validation tag by default 33 `SetFieldsRequiredByDefault` causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). A good place to activate this is a package init function or the main() function. 34 35 `SetNilPtrAllowedByRequired` causes validation to pass when struct fields marked by `required` are set to nil. This is disabled by default for consistency, but some packages that need to be able to determine between `nil` and `zero value` state can use this. If disabled, both `nil` and `zero` values cause validation errors. 36 37 ```go 38 import "github.com/tanqiangyes/govalidator" 39 40 func init() { 41 govalidator.SetFieldsRequiredByDefault(true) 42 } 43 ``` 44 45 Here's some code to explain it: 46 ```go 47 // this struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): 48 type exampleStruct struct { 49 Name string `` 50 Email string `valid:"email"` 51 } 52 53 // this, however, will only fail when Email is empty or an invalid email address: 54 type exampleStruct2 struct { 55 Name string `valid:"-"` 56 Email string `valid:"email"` 57 } 58 59 // lastly, this will only fail when Email is an invalid email address but not when it's empty: 60 type exampleStruct2 struct { 61 Name string `valid:"-"` 62 Email string `valid:"email,optional"` 63 } 64 ``` 65 66 #### Recent breaking changes (see [#123](https://github.com/tanqiangyes/govalidator/pull/123)) 67 ##### Custom validator function signature 68 A context was added as the second parameter, for structs this is the object being validated – this makes dependent validation possible. 69 ```go 70 import "github.com/tanqiangyes/govalidator" 71 72 // old signature 73 func(i interface{}) bool 74 75 // new signature 76 func(i interface{}, o interface{}) bool 77 ``` 78 79 ##### Adding a custom validator 80 This was changed to prevent data races when accessing custom validators. 81 ```go 82 import "github.com/tanqiangyes/govalidator" 83 84 // before 85 govalidator.CustomTypeTagMap["customByteArrayValidator"] = func(i interface{}, o interface{}) bool { 86 // ... 87 } 88 89 // after 90 govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, o interface{}) bool { 91 // ... 92 }) 93 ``` 94 95 #### List of functions: 96 ```go 97 func Abs(value float64) float64 98 func BlackList(str, chars string) string 99 func ByteLength(str string, params ...string) bool 100 func CamelCaseToUnderscore(str string) string 101 func Contains(str, substring string) bool 102 func Count(array []interface{}, iterator ConditionIterator) int 103 func Each(array []interface{}, iterator Iterator) 104 func ErrorByField(e error, field string) string 105 func ErrorsByField(e error) map[string]string 106 func Filter(array []interface{}, iterator ConditionIterator) []interface{} 107 func Find(array []interface{}, iterator ConditionIterator) interface{} 108 func GetLine(s string, index int) (string, error) 109 func GetLines(s string) []string 110 func HasLowerCase(str string) bool 111 func HasUpperCase(str string) bool 112 func HasWhitespace(str string) bool 113 func HasWhitespaceOnly(str string) bool 114 func InRange(value interface{}, left interface{}, right interface{}) bool 115 func InRangeFloat32(value, left, right float32) bool 116 func InRangeFloat64(value, left, right float64) bool 117 func InRangeInt(value, left, right interface{}) bool 118 func IsASCII(str string) bool 119 func IsAlpha(str string) bool 120 func IsAlphanumeric(str string) bool 121 func IsBase64(str string) bool 122 func IsByteLength(str string, min, max int) bool 123 func IsCIDR(str string) bool 124 func IsCRC32(str string) bool 125 func IsCRC32b(str string) bool 126 func IsCreditCard(str string) bool 127 func IsDNSName(str string) bool 128 func IsDataURI(str string) bool 129 func IsDialString(str string) bool 130 func IsDivisibleBy(str, num string) bool 131 func IsEmail(str string) bool 132 func IsExistingEmail(email string) bool 133 func IsFilePath(str string) (bool, int) 134 func IsFloat(str string) bool 135 func IsFullWidth(str string) bool 136 func IsHalfWidth(str string) bool 137 func IsHash(str string, algorithm string) bool 138 func IsHexadecimal(str string) bool 139 func IsHexcolor(str string) bool 140 func IsHost(str string) bool 141 func IsIP(str string) bool 142 func IsIPv4(str string) bool 143 func IsIPv6(str string) bool 144 func IsISBN(str string, version int) bool 145 func IsISBN10(str string) bool 146 func IsISBN13(str string) bool 147 func IsISO3166Alpha2(str string) bool 148 func IsISO3166Alpha3(str string) bool 149 func IsISO4217(str string) bool 150 func IsISO693Alpha2(str string) bool 151 func IsISO693Alpha3b(str string) bool 152 func IsIn(str string, params ...string) bool 153 func IsInRaw(str string, params ...string) bool 154 func IsInt(str string) bool 155 func IsJSON(str string) bool 156 func IsLatitude(str string) bool 157 func IsLongitude(str string) bool 158 func IsLowerCase(str string) bool 159 func IsMAC(str string) bool 160 func IsMD4(str string) bool 161 func IsMD5(str string) bool 162 func IsMagnetURI(str string) bool 163 func IsMongoID(str string) bool 164 func IsMultibyte(str string) bool 165 func IsNatural(value float64) bool 166 func IsNegative(value float64) bool 167 func IsNonNegative(value float64) bool 168 func IsNonPositive(value float64) bool 169 func IsNotNull(str string) bool 170 func IsNull(str string) bool 171 func IsNumeric(str string) bool 172 func IsPort(str string) bool 173 func IsPositive(value float64) bool 174 func IsPrintableASCII(str string) bool 175 func IsRFC3339(str string) bool 176 func IsRFC3339WithoutZone(str string) bool 177 func IsRGBcolor(str string) bool 178 func IsRegex(str string) bool 179 func IsRequestURI(rawurl string) bool 180 func IsRequestURL(rawurl string) bool 181 func IsRipeMD128(str string) bool 182 func IsRipeMD160(str string) bool 183 func IsRsaPub(str string, params ...string) bool 184 func IsRsaPublicKey(str string, keylen int) bool 185 func IsSHA1(str string) bool 186 func IsSHA256(str string) bool 187 func IsSHA384(str string) bool 188 func IsSHA512(str string) bool 189 func IsSSN(str string) bool 190 func IsSemver(str string) bool 191 func IsTiger128(str string) bool 192 func IsTiger160(str string) bool 193 func IsTiger192(str string) bool 194 func IsTime(str string, format string) bool 195 func IsType(v interface{}, params ...string) bool 196 func IsURL(str string) bool 197 func IsUTFDigit(str string) bool 198 func IsUTFLetter(str string) bool 199 func IsUTFLetterNumeric(str string) bool 200 func IsUTFNumeric(str string) bool 201 func IsUUID(str string) bool 202 func IsUUIDv3(str string) bool 203 func IsUUIDv4(str string) bool 204 func IsUUIDv5(str string) bool 205 func IsULID(str string) bool 206 func IsUnixTime(str string) bool 207 func IsUpperCase(str string) bool 208 func IsVariableWidth(str string) bool 209 func IsWhole(value float64) bool 210 func LeftTrim(str, chars string) string 211 func Map(array []interface{}, iterator ResultIterator) []interface{} 212 func Matches(str, pattern string) bool 213 func MaxStringLength(str string, params ...string) bool 214 func MinStringLength(str string, params ...string) bool 215 func NormalizeEmail(str string) (string, error) 216 func PadBoth(str string, padStr string, padLen int) string 217 func PadLeft(str string, padStr string, padLen int) string 218 func PadRight(str string, padStr string, padLen int) string 219 func PrependPathToErrors(err error, path string) error 220 func Range(str string, params ...string) bool 221 func RemoveTags(s string) string 222 func ReplacePattern(str, pattern, replace string) string 223 func Reverse(s string) string 224 func RightTrim(str, chars string) string 225 func RuneLength(str string, params ...string) bool 226 func SafeFileName(str string) string 227 func SetFieldsRequiredByDefault(value bool) 228 func SetNilPtrAllowedByRequired(value bool) 229 func Sign(value float64) float64 230 func StringLength(str string, params ...string) bool 231 func StringMatches(s string, params ...string) bool 232 func StripLow(str string, keepNewLines bool) string 233 func ToBoolean(str string) (bool, error) 234 func ToFloat(str string) (float64, error) 235 func ToInt(value interface{}) (res int64, err error) 236 func ToJSON(obj interface{}) (string, error) 237 func ToString(obj interface{}) string 238 func Trim(str, chars string) string 239 func Truncate(str string, length int, ending string) string 240 func TruncatingErrorf(str string, args ...interface{}) error 241 func UnderscoreToCamelCase(s string) string 242 func ValidateMap(inputMap map[string]interface{}, validationMap map[string]interface{}) (bool, error) 243 func ValidateStruct(s interface{}) (bool, error) 244 func WhiteList(str, chars string) string 245 type ConditionIterator 246 type CustomTypeValidator 247 type Error 248 func (e Error) Error() string 249 type Errors 250 func (es Errors) Error() string 251 func (es Errors) Errors() []error 252 type ISO3166Entry 253 type ISO693Entry 254 type InterfaceParamValidator 255 type Iterator 256 type ParamValidator 257 type ResultIterator 258 type UnsupportedTypeError 259 func (e *UnsupportedTypeError) Error() string 260 type Validator 261 ``` 262 263 #### Examples 264 ###### IsURL 265 ```go 266 println(govalidator.IsURL(`http://user@pass:domain.com/path/page`)) 267 ``` 268 ###### IsType 269 ```go 270 println(govalidator.IsType("Bob", "string")) 271 println(govalidator.IsType(1, "int")) 272 i := 1 273 println(govalidator.IsType(&i, "*int")) 274 ``` 275 276 IsType can be used through the tag `type` which is essential for map validation: 277 ```go 278 type User struct { 279 Name string `valid:"type(string)"` 280 Age int `valid:"type(int)"` 281 Meta interface{} `valid:"type(string)"` 282 } 283 result, err := govalidator.ValidateStruct(User{"Bob", 20, "meta"}) 284 if err != nil { 285 println("error: " + err.Error()) 286 } 287 println(result) 288 ``` 289 ###### ToString 290 ```go 291 type User struct { 292 FirstName string 293 LastName string 294 } 295 296 str := govalidator.ToString(&User{"John", "Juan"}) 297 println(str) 298 ``` 299 ###### Each, Map, Filter, Count for slices 300 Each iterates over the slice/array and calls Iterator for every item 301 ```go 302 data := []interface{}{1, 2, 3, 4, 5} 303 var fn govalidator.Iterator = func(value interface{}, index int) { 304 println(value.(int)) 305 } 306 govalidator.Each(data, fn) 307 ``` 308 ```go 309 data := []interface{}{1, 2, 3, 4, 5} 310 var fn govalidator.ResultIterator = func(value interface{}, index int) interface{} { 311 return value.(int) * 3 312 } 313 _ = govalidator.Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15} 314 ``` 315 ```go 316 data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} 317 var fn govalidator.ConditionIterator = func(value interface{}, index int) bool { 318 return value.(int)%2 == 0 319 } 320 _ = govalidator.Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10} 321 _ = govalidator.Count(data, fn) // result = 5 322 ``` 323 ###### ValidateStruct [#2](https://github.com/tanqiangyes/govalidator/pull/2) 324 If you want to validate structs, you can use tag `valid` for any field in your structure. All validators used with this field in one tag are separated by comma. If you want to skip validation, place `-` in your tag. If you need a validator that is not on the list below, you can add it like this: 325 ```go 326 govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { 327 return str == "duck" 328 }) 329 ``` 330 For completely custom validators (interface-based), see below. 331 332 Here is a list of available validators for struct fields (validator - used function): 333 ```go 334 "email": IsEmail, 335 "url": IsURL, 336 "dialstring": IsDialString, 337 "requrl": IsRequestURL, 338 "requri": IsRequestURI, 339 "alpha": IsAlpha, 340 "utfletter": IsUTFLetter, 341 "alphanum": IsAlphanumeric, 342 "utfletternum": IsUTFLetterNumeric, 343 "numeric": IsNumeric, 344 "utfnumeric": IsUTFNumeric, 345 "utfdigit": IsUTFDigit, 346 "hexadecimal": IsHexadecimal, 347 "hexcolor": IsHexcolor, 348 "rgbcolor": IsRGBcolor, 349 "lowercase": IsLowerCase, 350 "uppercase": IsUpperCase, 351 "int": IsInt, 352 "float": IsFloat, 353 "null": IsNull, 354 "uuid": IsUUID, 355 "uuidv3": IsUUIDv3, 356 "uuidv4": IsUUIDv4, 357 "uuidv5": IsUUIDv5, 358 "creditcard": IsCreditCard, 359 "isbn10": IsISBN10, 360 "isbn13": IsISBN13, 361 "json": IsJSON, 362 "multibyte": IsMultibyte, 363 "ascii": IsASCII, 364 "printableascii": IsPrintableASCII, 365 "fullwidth": IsFullWidth, 366 "halfwidth": IsHalfWidth, 367 "variablewidth": IsVariableWidth, 368 "base64": IsBase64, 369 "datauri": IsDataURI, 370 "ip": IsIP, 371 "port": IsPort, 372 "ipv4": IsIPv4, 373 "ipv6": IsIPv6, 374 "dns": IsDNSName, 375 "host": IsHost, 376 "mac": IsMAC, 377 "latitude": IsLatitude, 378 "longitude": IsLongitude, 379 "ssn": IsSSN, 380 "semver": IsSemver, 381 "rfc3339": IsRFC3339, 382 "rfc3339WithoutZone": IsRFC3339WithoutZone, 383 "ISO3166Alpha2": IsISO3166Alpha2, 384 "ISO3166Alpha3": IsISO3166Alpha3, 385 "ulid": IsULID, 386 ``` 387 Validators with parameters 388 389 ```go 390 "range(min|max)": Range, 391 "length(min|max)": ByteLength, 392 "runelength(min|max)": RuneLength, 393 "stringlength(min|max)": StringLength, 394 "matches(pattern)": StringMatches, 395 "in(string1|string2|...|stringN)": IsIn, 396 "rsapub(keylength)" : IsRsaPub, 397 "minstringlength(int): MinStringLength, 398 "maxstringlength(int): MaxStringLength, 399 ``` 400 Validators with parameters for any type 401 402 ```go 403 "type(type)": IsType, 404 ``` 405 406 And here is small example of usage: 407 ```go 408 type Post struct { 409 Title string `valid:"alphanum,required"` 410 Message string `valid:"duck,ascii"` 411 Message2 string `valid:"animal(dog)"` 412 AuthorIP string `valid:"ipv4"` 413 Date string `valid:"-"` 414 } 415 post := &Post{ 416 Title: "My Example Post", 417 Message: "duck", 418 Message2: "dog", 419 AuthorIP: "123.234.54.3", 420 } 421 422 // Add your own struct validation tags 423 govalidator.TagMap["duck"] = govalidator.Validator(func(str string) bool { 424 return str == "duck" 425 }) 426 427 // Add your own struct validation tags with parameter 428 govalidator.ParamTagMap["animal"] = govalidator.ParamValidator(func(str string, params ...string) bool { 429 species := params[0] 430 return str == species 431 }) 432 govalidator.ParamTagRegexMap["animal"] = regexp.MustCompile("^animal\\((\\w+)\\)$") 433 434 result, err := govalidator.ValidateStruct(post) 435 if err != nil { 436 println("error: " + err.Error()) 437 } 438 println(result) 439 ``` 440 ###### ValidateMap [#2](https://github.com/tanqiangyes/govalidator/pull/338) 441 If you want to validate maps, you can use the map to be validated and a validation map that contain the same tags used in ValidateStruct, both maps have to be in the form `map[string]interface{}` 442 443 So here is small example of usage: 444 ```go 445 var mapTemplate = map[string]interface{}{ 446 "name":"required,alpha", 447 "family":"required,alpha", 448 "email":"required,email", 449 "cell-phone":"numeric", 450 "address":map[string]interface{}{ 451 "line1":"required,alphanum", 452 "line2":"alphanum", 453 "postal-code":"numeric", 454 }, 455 } 456 457 var inputMap = map[string]interface{}{ 458 "name":"Bob", 459 "family":"Smith", 460 "email":"foo@bar.baz", 461 "address":map[string]interface{}{ 462 "line1":"", 463 "line2":"", 464 "postal-code":"", 465 }, 466 } 467 468 result, err := govalidator.ValidateMap(inputMap, mapTemplate) 469 if err != nil { 470 println("error: " + err.Error()) 471 } 472 println(result) 473 ``` 474 475 ###### WhiteList 476 ```go 477 // Remove all characters from string ignoring characters between "a" and "z" 478 println(govalidator.WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa") 479 ``` 480 481 ###### Custom validation functions 482 Custom validation using your own domain specific validators is also available - here's an example of how to use it: 483 ```go 484 import "github.com/tanqiangyes/govalidator" 485 486 type CustomByteArray [6]byte // custom types are supported and can be validated 487 488 type StructWithCustomByteArray struct { 489 ID CustomByteArray `valid:"customByteArrayValidator,customMinLengthValidator"` // multiple custom validators are possible as well and will be evaluated in sequence 490 Email string `valid:"email"` 491 CustomMinLength int `valid:"-"` 492 } 493 494 govalidator.CustomTypeTagMap.Set("customByteArrayValidator", func(i interface{}, context interface{}) bool { 495 switch v := context.(type) { // you can type switch on the context interface being validated 496 case StructWithCustomByteArray: 497 // you can check and validate against some other field in the context, 498 // return early or not validate against the context at all – your choice 499 case SomeOtherType: 500 // ... 501 default: 502 // expecting some other type? Throw/panic here or continue 503 } 504 505 switch v := i.(type) { // type switch on the struct field being validated 506 case CustomByteArray: 507 for _, e := range v { // this validator checks that the byte array is not empty, i.e. not all zeroes 508 if e != 0 { 509 return true 510 } 511 } 512 } 513 return false 514 }) 515 govalidator.CustomTypeTagMap.Set("customMinLengthValidator", func(i interface{}, context interface{}) bool { 516 switch v := context.(type) { // this validates a field against the value in another field, i.e. dependent validation 517 case StructWithCustomByteArray: 518 return len(v.ID) >= v.CustomMinLength 519 } 520 return false 521 }) 522 ``` 523 524 ###### Loop over Error() 525 By default .Error() returns all errors in a single String. To access each error you can do this: 526 ```go 527 if err != nil { 528 errs := err.(govalidator.Errors).Errors() 529 for _, e := range errs { 530 fmt.Println(e.Error()) 531 } 532 } 533 ``` 534 535 ###### Custom error messages 536 Custom error messages are supported via annotations by adding the `~` separator - here's an example of how to use it: 537 ```go 538 type Ticket struct { 539 Id int64 `json:"id"` 540 FirstName string `json:"firstname" valid:"required~First name is blank"` 541 } 542 ``` 543 544 #### Notes 545 Documentation is available here: [godoc.org](https://godoc.org/github.com/tanqiangyes/govalidator). 546 Full information about code coverage is also available here: [govalidator on gocover.io](http://gocover.io/github.com/tanqiangyes/govalidator). 547 548 #### Support 549 If you do have a contribution to the package, feel free to create a Pull Request or an Issue. 550 551 #### What to contribute 552 If you don't know what to do, there are some features and functions that need to be done 553 554 - [ ] Refactor code 555 - [ ] Edit docs and [README](https://github.com/tanqiangyes/govalidator/README.md): spellcheck, grammar and typo check 556 - [ ] Create actual list of contributors and projects that currently using this package 557 - [ ] Resolve [issues and bugs](https://github.com/tanqiangyes/govalidator/issues) 558 - [ ] Update actual [list of functions](https://github.com/tanqiangyes/govalidator#list-of-functions) 559 - [ ] Update [list of validators](https://github.com/tanqiangyes/govalidator#validatestruct-2) that available for `ValidateStruct` and add new 560 - [ ] Implement new validators: `IsFQDN`, `IsIMEI`, `IsPostalCode`, `IsISIN`, `IsISRC` etc 561 - [x] Implement [validation by maps](https://github.com/tanqiangyes/govalidator/issues/224) 562 - [ ] Implement fuzzing testing 563 - [ ] Implement some struct/map/array utilities 564 - [ ] Implement map/array validation 565 - [ ] Implement benchmarking 566 - [ ] Implement batch of examples 567 - [ ] Look at forks for new features and fixes 568 569 #### Advice 570 Feel free to create what you want, but keep in mind when you implement new features: 571 - Code must be clear and readable, names of variables/constants clearly describes what they are doing 572 - Public functions must be documented and described in source file and added to README.md to the list of available functions 573 - There are must be unit-tests for any new functions and improvements 574 575 ## Credits 576 ### Contributors 577 578 This project exists thanks to all the people who contribute. [[Contribute](CONTRIBUTING.md)]. 579 580 ## License 581 [](https://app.fossa.io/projects/git%2Bgithub.com%2Ftanqiangyes%2Fgovalidator?ref=badge_large)