github.com/tanqiangyes/govalidator@v0.0.5/validator.go (about) 1 // Package govalidator is package of validators and sanitizers for strings, structs and collections. 2 package govalidator 3 4 import ( 5 "bytes" 6 "crypto/rsa" 7 "crypto/x509" 8 "encoding/base64" 9 "encoding/json" 10 "encoding/pem" 11 "fmt" 12 "io/ioutil" 13 "net" 14 "net/url" 15 "reflect" 16 "regexp" 17 "sort" 18 "strconv" 19 "strings" 20 "time" 21 "unicode" 22 "unicode/utf8" 23 ) 24 25 var ( 26 fieldsRequiredByDefault bool 27 nilPtrAllowedByRequired = false 28 notNumberRegexp = regexp.MustCompile("[^0-9]+") 29 whiteSpacesAndMinus = regexp.MustCompile(`[\s-]+`) 30 paramsRegexp = regexp.MustCompile(`\(.*\)$`) 31 ) 32 33 const maxURLRuneCount = 2083 34 35 const minURLRuneCount = 3 36 37 const rfc3339WithoutZone = "2006-01-02T15:04:05" 38 39 // SetFieldsRequiredByDefault causes validation to fail when struct fields 40 // do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). 41 // This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter): 42 // 43 // type exampleStruct struct { 44 // Name string `` 45 // Email string `valid:"email"` 46 // 47 // This, however, will only fail when Email is empty or an invalid email address: 48 // 49 // type exampleStruct2 struct { 50 // Name string `valid:"-"` 51 // Email string `valid:"email"` 52 // 53 // Lastly, this will only fail when Email is an invalid email address but not when it's empty: 54 // 55 // type exampleStruct2 struct { 56 // Name string `valid:"-"` 57 // Email string `valid:"email,optional"` 58 func SetFieldsRequiredByDefault(value bool) { 59 fieldsRequiredByDefault = value 60 } 61 62 // SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. 63 // The validation will still reject ptr fields in their zero value state. Example with this enabled: 64 // 65 // type exampleStruct struct { 66 // Name *string `valid:"required"` 67 // 68 // With `Name` set to "", this will be considered invalid input and will cause a validation error. 69 // With `Name` set to nil, this will be considered valid by validation. 70 // By default this is disabled. 71 func SetNilPtrAllowedByRequired(value bool) { 72 nilPtrAllowedByRequired = value 73 } 74 75 // IsEmail checks if the string is an email. 76 func IsEmail[T ~string](str T) bool { 77 // TODO uppercase letters are not supported 78 return rxEmail.MatchString(string(str)) 79 } 80 81 // IsExistingEmail checks if the string is an email of existing domain 82 func IsExistingEmail[T ~string](email T) bool { 83 84 if len(email) < 6 || len(email) > 254 { 85 return false 86 } 87 at := strings.LastIndex(string(email), "@") 88 if at <= 0 || at > len(email)-3 { 89 return false 90 } 91 user := email[:at] 92 host := email[at+1:] 93 if len(user) > 64 { 94 return false 95 } 96 switch host { 97 case "localhost", "example.com": 98 return true 99 } 100 if userDotRegexp.MatchString(string(user)) || !userRegexp.MatchString(string(user)) || !hostRegexp.MatchString(string(host)) { 101 return false 102 } 103 if _, err := net.LookupMX(string(host)); err != nil { 104 if _, err := net.LookupIP(string(host)); err != nil { 105 return false 106 } 107 } 108 109 return true 110 } 111 112 // IsURL checks if the string is an URL. 113 func IsURL[T ~string](s T) bool { 114 str := string(s) 115 if str == "" || utf8.RuneCountInString(str) >= maxURLRuneCount || len(str) <= minURLRuneCount || strings.HasPrefix(str, ".") { 116 return false 117 } 118 strTemp := str 119 if strings.Contains(str, ":") && !strings.Contains(str, "://") { 120 // support no indicated urlscheme but with colon for port number 121 // http:// is appended so url.Parse will succeed, strTemp used so it does not impact rxURL.MatchString 122 strTemp = "http://" + str 123 } 124 u, err := url.Parse(strTemp) 125 if err != nil { 126 return false 127 } 128 if strings.HasPrefix(u.Host, ".") { 129 return false 130 } 131 if u.Host == "" && (u.Path != "" && !strings.Contains(u.Path, ".")) { 132 return false 133 } 134 return rxURL.MatchString(str) 135 } 136 137 // IsRequestURL checks if the string rawurl, assuming 138 // it was received in an HTTP request, is a valid 139 // URL confirm to RFC 3986 140 func IsRequestURL[T ~string](rawurl T) bool { 141 url, err := url.ParseRequestURI(string(rawurl)) 142 if err != nil { 143 return false // Couldn't even parse the rawurl 144 } 145 if len(url.Scheme) == 0 { 146 return false // No Scheme found 147 } 148 return true 149 } 150 151 // IsRequestURI checks if the string rawurl, assuming 152 // it was received in an HTTP request, is an 153 // absolute URI or an absolute path. 154 func IsRequestURI[T ~string](rawurl T) bool { 155 _, err := url.ParseRequestURI(string(rawurl)) 156 return err == nil 157 } 158 159 // IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid. 160 func IsAlpha[T ~string](str T) bool { 161 if IsNull(str) { 162 return true 163 } 164 return rxAlpha.MatchString(string(str)) 165 } 166 167 // IsUTFLetter checks if the string contains only unicode letter characters. 168 // Similar to IsAlpha but for all languages. Empty string is valid. 169 func IsUTFLetter[T ~string](str T) bool { 170 if IsNull(str) { 171 return true 172 } 173 174 for _, c := range str { 175 if !unicode.IsLetter(c) { 176 return false 177 } 178 } 179 return true 180 181 } 182 183 // IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid. 184 func IsAlphanumeric[T ~string](str T) bool { 185 if IsNull(str) { 186 return true 187 } 188 return rxAlphanumeric.MatchString(string(str)) 189 } 190 191 // IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid. 192 func IsUTFLetterNumeric[T ~string](str T) bool { 193 if IsNull(str) { 194 return true 195 } 196 for _, c := range str { 197 if !unicode.IsLetter(c) && !unicode.IsNumber(c) { // letters && numbers are ok 198 return false 199 } 200 } 201 return true 202 203 } 204 205 // IsNumeric checks if the string contains only numbers. Empty string is valid. 206 func IsNumeric[T ~string](str T) bool { 207 if IsNull(str) { 208 return true 209 } 210 return rxNumeric.MatchString(string(str)) 211 } 212 213 // IsUTFNumeric checks if the string contains only unicode numbers of any kind. 214 // Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid. 215 func IsUTFNumeric[T ~string](s T) bool { 216 if IsNull(s) { 217 return true 218 } 219 str := string(s) 220 if strings.IndexAny(str, "+-") > 0 { 221 return false 222 } 223 if len(str) > 1 { 224 str = strings.TrimPrefix(str, "-") 225 str = strings.TrimPrefix(str, "+") 226 } 227 for _, c := range str { 228 if !unicode.IsNumber(c) { // numbers && minus sign are ok 229 return false 230 } 231 } 232 return true 233 234 } 235 236 // IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid. 237 func IsUTFDigit[T ~string](s T) bool { 238 if IsNull(s) { 239 return true 240 } 241 str := string(s) 242 if strings.IndexAny(str, "+-") > 0 { 243 return false 244 } 245 if len(str) > 1 { 246 str = strings.TrimPrefix(str, "-") 247 str = strings.TrimPrefix(str, "+") 248 } 249 for _, c := range str { 250 if !unicode.IsDigit(c) { // digits && minus sign are ok 251 return false 252 } 253 } 254 return true 255 256 } 257 258 // IsHexadecimal checks if the string is a hexadecimal number. 259 func IsHexadecimal[T ~string](str T) bool { 260 return rxHexadecimal.MatchString(string(str)) 261 } 262 263 // IsHexcolor checks if the string is a hexadecimal color. 264 func IsHexcolor[T ~string](str string) bool { 265 return rxHexcolor.MatchString(str) 266 } 267 268 // IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB). 269 func IsRGBcolor[T ~string](str string) bool { 270 return rxRGBcolor.MatchString(str) 271 } 272 273 // IsLowerCase checks if the string is lowercase. Empty string is valid. 274 func IsLowerCase[T ~string](str string) bool { 275 if IsNull(str) { 276 return true 277 } 278 return str == strings.ToLower(str) 279 } 280 281 // IsUpperCase checks if the string is uppercase. Empty string is valid. 282 func IsUpperCase[T ~string](str string) bool { 283 if IsNull(str) { 284 return true 285 } 286 return str == strings.ToUpper(str) 287 } 288 289 // HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid. 290 func HasLowerCase[T ~string](str string) bool { 291 if IsNull(str) { 292 return true 293 } 294 return rxHasLowerCase.MatchString(str) 295 } 296 297 // HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid. 298 func HasUpperCase[T ~string](str string) bool { 299 if IsNull(str) { 300 return true 301 } 302 return rxHasUpperCase.MatchString(str) 303 } 304 305 // IsInt checks if the string is an integer. Empty string is valid. 306 func IsInt[T ~string](str string) bool { 307 if IsNull(str) { 308 return true 309 } 310 return rxInt.MatchString(str) 311 } 312 313 // IsFloat checks if the string is a float. 314 func IsFloat[T ~string](str string) bool { 315 return str != "" && rxFloat.MatchString(str) 316 } 317 318 // IsDivisibleBy checks if the string is a number that's divisible by another. 319 // If second argument is not valid integer or zero, it's return false. 320 // Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero). 321 func IsDivisibleBy[T ~string](str, num T) bool { 322 f, _ := ToNumber[T, float64](str) 323 p := int64(f) 324 q, _ := ToInt(num) 325 if q == 0 { 326 return false 327 } 328 return (p == 0) || (p%q == 0) 329 } 330 331 // IsNull checks if the string is null. 332 func IsNull[T ~string](str T) bool { 333 return len(str) == 0 334 } 335 336 // IsNotNull checks if the string is not null. 337 func IsNotNull[T ~string](str T) bool { 338 return !IsNull(str) 339 } 340 341 // HasWhitespaceOnly checks the string only contains whitespace 342 func HasWhitespaceOnly[T ~string](str T) bool { 343 return len(str) > 0 && rxHasWhitespaceOnly.MatchString(string(str)) 344 } 345 346 // HasWhitespace checks if the string contains any whitespace 347 func HasWhitespace[T ~string](str T) bool { 348 return len(str) > 0 && rxHasWhitespace.MatchString(string(str)) 349 } 350 351 // IsByteLength checks if the string's length (in bytes) falls in a range. 352 func IsByteLength[T ~string](str T, min, max int) bool { 353 return len(str) >= min && len(str) <= max 354 } 355 356 // IsUUIDv3 checks if the string is a UUID version 3. 357 func IsUUIDv3[T ~string](str T) bool { 358 return rxUUID3.MatchString(string(str)) 359 } 360 361 // IsUUIDv4 checks if the string is a UUID version 4. 362 func IsUUIDv4[T ~string](str T) bool { 363 return rxUUID4.MatchString(string(str)) 364 } 365 366 // IsUUIDv5 checks if the string is a UUID version 5. 367 func IsUUIDv5[T ~string](str T) bool { 368 return rxUUID5.MatchString(string(str)) 369 } 370 371 // IsUUID checks if the string is a UUID (version 3, 4 or 5). 372 func IsUUID[T ~string](str T) bool { 373 return rxUUID.MatchString(string(str)) 374 } 375 376 // Byte to index table for O(1) lookups when unmarshaling. 377 // We use 0xFF as sentinel value for invalid indexes. 378 var ulidDec = [...]byte{ 379 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 380 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 381 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 382 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 383 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x01, 384 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 385 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 386 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 0x15, 0xFF, 387 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 0x1D, 0x1E, 388 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x0A, 0x0B, 0x0C, 389 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0xFF, 0x12, 0x13, 0xFF, 0x14, 390 0x15, 0xFF, 0x16, 0x17, 0x18, 0x19, 0x1A, 0xFF, 0x1B, 0x1C, 391 0x1D, 0x1E, 0x1F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 392 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 393 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 394 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 395 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 396 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 397 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 398 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 399 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 400 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 401 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 402 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 403 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 404 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 405 } 406 407 // EncodedSize is the length of a text encoded ULID. 408 const ulidEncodedSize = 26 409 410 // IsULID checks if the string is a ULID. 411 // 412 // Implementation got from: 413 // 414 // https://github.com/oklog/ulid (Apache-2.0 License) 415 func IsULID[T ~string](str T) bool { 416 // Check if a base32 encoded ULID is the right length. 417 if len(str) != ulidEncodedSize { 418 return false 419 } 420 421 // Check if all the characters in a base32 encoded ULID are part of the 422 // expected base32 character set. 423 if ulidDec[str[0]] == 0xFF || 424 ulidDec[str[1]] == 0xFF || 425 ulidDec[str[2]] == 0xFF || 426 ulidDec[str[3]] == 0xFF || 427 ulidDec[str[4]] == 0xFF || 428 ulidDec[str[5]] == 0xFF || 429 ulidDec[str[6]] == 0xFF || 430 ulidDec[str[7]] == 0xFF || 431 ulidDec[str[8]] == 0xFF || 432 ulidDec[str[9]] == 0xFF || 433 ulidDec[str[10]] == 0xFF || 434 ulidDec[str[11]] == 0xFF || 435 ulidDec[str[12]] == 0xFF || 436 ulidDec[str[13]] == 0xFF || 437 ulidDec[str[14]] == 0xFF || 438 ulidDec[str[15]] == 0xFF || 439 ulidDec[str[16]] == 0xFF || 440 ulidDec[str[17]] == 0xFF || 441 ulidDec[str[18]] == 0xFF || 442 ulidDec[str[19]] == 0xFF || 443 ulidDec[str[20]] == 0xFF || 444 ulidDec[str[21]] == 0xFF || 445 ulidDec[str[22]] == 0xFF || 446 ulidDec[str[23]] == 0xFF || 447 ulidDec[str[24]] == 0xFF || 448 ulidDec[str[25]] == 0xFF { 449 return false 450 } 451 452 // Check if the first character in a base32 encoded ULID will overflow. This 453 // happens because the base32 representation encodes 130 bits, while the 454 // ULID is only 128 bits. 455 // 456 // See https://github.com/oklog/ulid/issues/9 for details. 457 if str[0] > '7' { 458 return false 459 } 460 return true 461 } 462 463 // IsCreditCard checks if the string is a credit card. 464 func IsCreditCard[T ~string](str T) bool { 465 sanitized := whiteSpacesAndMinus.ReplaceAllString(string(str), "") 466 if !rxCreditCard.MatchString(sanitized) { 467 return false 468 } 469 470 number, _ := ToInt(sanitized) 471 number, lastDigit := number/10, number%10 472 473 var sum int64 474 for i := 0; number > 0; i++ { 475 digit := number % 10 476 477 if i%2 == 0 { 478 digit *= 2 479 if digit > 9 { 480 digit -= 9 481 } 482 } 483 484 sum += digit 485 number = number / 10 486 } 487 488 return (sum+lastDigit)%10 == 0 489 } 490 491 // IsISBN10 checks if the string is an ISBN version 10. 492 func IsISBN10[T ~string](str T) bool { 493 return IsISBN(str, 10) 494 } 495 496 // IsISBN13 checks if the string is an ISBN version 13. 497 func IsISBN13[T ~string](str T) bool { 498 return IsISBN(str, 13) 499 } 500 501 // IsISBN checks if the string is an ISBN (version 10 or 13). 502 // If version value is not equal to 10 or 13, it will be checks both variants. 503 func IsISBN[T ~string](str T, version int) bool { 504 sanitized := whiteSpacesAndMinus.ReplaceAllString(string(str), "") 505 var checksum int32 506 var i int32 507 if version == 10 { 508 if !rxISBN10.MatchString(sanitized) { 509 return false 510 } 511 for i = 0; i < 9; i++ { 512 checksum += (i + 1) * int32(sanitized[i]-'0') 513 } 514 if sanitized[9] == 'X' { 515 checksum += 10 * 10 516 } else { 517 checksum += 10 * int32(sanitized[9]-'0') 518 } 519 if checksum%11 == 0 { 520 return true 521 } 522 return false 523 } else if version == 13 { 524 if !rxISBN13.MatchString(sanitized) { 525 return false 526 } 527 factor := []int32{1, 3} 528 for i = 0; i < 12; i++ { 529 checksum += factor[i%2] * int32(sanitized[i]-'0') 530 } 531 return (int32(sanitized[12]-'0'))-((10-(checksum%10))%10) == 0 532 } 533 return IsISBN(str, 10) || IsISBN(str, 13) 534 } 535 536 // IsJSON checks if the string is valid JSON (note: uses json.Unmarshal). 537 func IsJSON[T ~string](str T) bool { 538 var js json.RawMessage 539 return json.Unmarshal([]byte(str), &js) == nil 540 } 541 542 // IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid. 543 func IsMultibyte[T ~string](str T) bool { 544 if IsNull(str) { 545 return true 546 } 547 return rxMultibyte.MatchString(string(str)) 548 } 549 550 // IsASCII checks if the string contains ASCII chars only. Empty string is valid. 551 func IsASCII[T ~string](str T) bool { 552 if IsNull(str) { 553 return true 554 } 555 return rxASCII.MatchString(string(str)) 556 } 557 558 // IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid. 559 func IsPrintableASCII[T ~string](str T) bool { 560 if IsNull(str) { 561 return true 562 } 563 return rxPrintableASCII.MatchString(string(str)) 564 } 565 566 // IsFullWidth checks if the string contains any full-width chars. Empty string is valid. 567 func IsFullWidth[T ~string](str T) bool { 568 if IsNull(str) { 569 return true 570 } 571 return rxFullWidth.MatchString(string(str)) 572 } 573 574 // IsHalfWidth checks if the string contains any half-width chars. Empty string is valid. 575 func IsHalfWidth[T ~string](str T) bool { 576 if IsNull(str) { 577 return true 578 } 579 return rxHalfWidth.MatchString(string(str)) 580 } 581 582 // IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid. 583 func IsVariableWidth[T ~string](str T) bool { 584 if IsNull(str) { 585 return true 586 } 587 return rxHalfWidth.MatchString(string(str)) && rxFullWidth.MatchString(string(str)) 588 } 589 590 // IsBase64 checks if a string is base64 encoded. 591 func IsBase64[T ~string](str T) bool { 592 return rxBase64.MatchString(string(str)) 593 } 594 595 // IsFilePath checks is a string is Win or Unix file path and returns it's type. 596 func IsFilePath[T ~string](str T) (bool, int) { 597 if rxWinPath.MatchString(string(str)) { 598 // check windows path limit see: 599 // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath 600 if len(str[3:]) > 32767 { 601 return false, Win 602 } 603 return true, Win 604 } else if rxUnixPath.MatchString(string(str)) { 605 return true, Unix 606 } 607 return false, Unknown 608 } 609 610 // IsWinFilePath checks both relative & absolute paths in Windows 611 func IsWinFilePath[T ~string](str T) bool { 612 if rxARWinPath.MatchString(string(str)) { 613 // check windows path limit see: 614 // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maxpath 615 if len(str[3:]) > 32767 { 616 return false 617 } 618 return true 619 } 620 return false 621 } 622 623 // IsUnixFilePath checks both relative & absolute paths in Unix 624 func IsUnixFilePath[T ~string](str T) bool { 625 if rxARUnixPath.MatchString(string(str)) { 626 return true 627 } 628 return false 629 } 630 631 // IsDataURI checks if a string is base64 encoded data URI such as an image 632 func IsDataURI[T ~string](str T) bool { 633 dataURI := strings.Split(string(str), ",") 634 if !rxDataURI.MatchString(dataURI[0]) { 635 return false 636 } 637 return IsBase64(dataURI[1]) 638 } 639 640 // IsMagnetURI checks if a string is valid magnet URI 641 func IsMagnetURI[T ~string](str T) bool { 642 return rxMagnetURI.MatchString(string(str)) 643 } 644 645 // IsISO3166Alpha2 checks if a string is valid two-letter country code 646 func IsISO3166Alpha2[T ~string](str T) bool { 647 for _, entry := range ISO3166List { 648 if string(str) == entry.Alpha2Code { 649 return true 650 } 651 } 652 return false 653 } 654 655 // IsISO3166Alpha3 checks if a string is valid three-letter country code 656 func IsISO3166Alpha3[T ~string](str T) bool { 657 for _, entry := range ISO3166List { 658 if string(str) == entry.Alpha3Code { 659 return true 660 } 661 } 662 return false 663 } 664 665 // IsISO693Alpha2 checks if a string is valid two-letter language code 666 func IsISO693Alpha2[T ~string](str T) bool { 667 for _, entry := range ISO693List { 668 if string(str) == entry.Alpha2Code { 669 return true 670 } 671 } 672 return false 673 } 674 675 // IsISO693Alpha3b checks if a string is valid three-letter language code 676 func IsISO693Alpha3b[T ~string](str T) bool { 677 for _, entry := range ISO693List { 678 if string(str) == entry.Alpha3bCode { 679 return true 680 } 681 } 682 return false 683 } 684 685 // IsDNSName will validate the given string as a DNS name 686 func IsDNSName[T ~string](str T) bool { 687 if string(str) == "" || len(strings.Replace(string(str), ".", "", -1)) > 255 { 688 // constraints already violated 689 return false 690 } 691 return !IsIP(string(str)) && rxDNSName.MatchString(string(str)) 692 } 693 694 // IsHash checks if a string is a hash of type algorithm. 695 // Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b'] 696 func IsHash[T ~string](str T, algorithm T) bool { 697 var lens string 698 algo := strings.ToLower(string(algorithm)) 699 700 if algo == "crc32" || algo == "crc32b" { 701 lens = "8" 702 } else if algo == "md5" || algo == "md4" || algo == "ripemd128" || algo == "tiger128" { 703 lens = "32" 704 } else if algo == "sha1" || algo == "ripemd160" || algo == "tiger160" { 705 lens = "40" 706 } else if algo == "tiger192" { 707 lens = "48" 708 } else if algo == "sha3-224" { 709 lens = "56" 710 } else if algo == "sha256" || algo == "sha3-256" { 711 lens = "64" 712 } else if algo == "sha384" || algo == "sha3-384" { 713 lens = "96" 714 } else if algo == "sha512" || algo == "sha3-512" { 715 lens = "128" 716 } else { 717 return false 718 } 719 720 return Matches(str, T("^[a-f0-9]{"+lens+"}$")) 721 } 722 723 // IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")` 724 func IsSHA3224[T ~string](str T) bool { 725 return IsHash(string(str), "sha3-224") 726 } 727 728 // IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")` 729 func IsSHA3256[T ~string](str T) bool { 730 return IsHash(string(str), "sha3-256") 731 } 732 733 // IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")` 734 func IsSHA3384[T ~string](str T) bool { 735 return IsHash(string(str), "sha3-384") 736 } 737 738 // IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")` 739 func IsSHA3512[T ~string](str T) bool { 740 return IsHash(string(str), "sha3-512") 741 } 742 743 // IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")` 744 func IsSHA512[T ~string](str T) bool { 745 return IsHash(string(str), "sha512") 746 } 747 748 // IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")` 749 func IsSHA384[T ~string](str T) bool { 750 return IsHash(string(str), "sha384") 751 } 752 753 // IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")` 754 func IsSHA256[T ~string](str T) bool { 755 return IsHash(string(str), "sha256") 756 } 757 758 // IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")` 759 func IsTiger192[T ~string](str T) bool { 760 return IsHash(string(str), "tiger192") 761 } 762 763 // IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")` 764 func IsTiger160[T ~string](str T) bool { 765 return IsHash(string(str), "tiger160") 766 } 767 768 // IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")` 769 func IsRipeMD160[T ~string](str T) bool { 770 return IsHash(string(str), "ripemd160") 771 } 772 773 // IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")` 774 func IsSHA1[T ~string](str T) bool { 775 return IsHash(string(str), "sha1") 776 } 777 778 // IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")` 779 func IsTiger128[T ~string](str T) bool { 780 return IsHash(string(str), "tiger128") 781 } 782 783 // IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")` 784 func IsRipeMD128[T ~string](str T) bool { 785 return IsHash(string(str), "ripemd128") 786 } 787 788 // IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")` 789 func IsCRC32[T ~string](str T) bool { 790 return IsHash(string(str), "crc32") 791 } 792 793 // IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")` 794 func IsCRC32b[T ~string](str T) bool { 795 return IsHash(string(str), "crc32b") 796 } 797 798 // IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")` 799 func IsMD5[T ~string](str T) bool { 800 return IsHash(string(str), "md5") 801 } 802 803 // IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")` 804 func IsMD4[T ~string](str T) bool { 805 return IsHash(string(str), "md4") 806 } 807 808 // IsDialString validates the given string for usage with the various Dial() functions 809 func IsDialString[T ~string](str T) bool { 810 if h, p, err := net.SplitHostPort(string(str)); err == nil && h != "" && p != "" && (IsDNSName(h) || IsIP(h)) && IsPort(p) { 811 return true 812 } 813 814 return false 815 } 816 817 // IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP` 818 func IsIP[T ~string](str T) bool { 819 return net.ParseIP(string(str)) != nil 820 } 821 822 // IsPort checks if a string represents a valid port 823 func IsPort[T ~string](str T) bool { 824 if i, err := strconv.Atoi(string(str)); err == nil && i > 0 && i < 65536 { 825 return true 826 } 827 return false 828 } 829 830 // IsIPv4 checks if the string is an IP version 4. 831 func IsIPv4[T ~string](str T) bool { 832 ip := net.ParseIP(string(str)) 833 return ip != nil && strings.Contains(string(str), ".") 834 } 835 836 // IsIPv6 checks if the string is an IP version 6. 837 func IsIPv6[T ~string](str T) bool { 838 ip := net.ParseIP(string(str)) 839 return ip != nil && strings.Contains(string(str), ":") 840 } 841 842 // IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6) 843 func IsCIDR[T ~string](str T) bool { 844 _, _, err := net.ParseCIDR(string(str)) 845 return err == nil 846 } 847 848 // IsMAC checks if a string is valid MAC address. 849 // Possible MAC formats: 850 // 01:23:45:67:89:ab 851 // 01:23:45:67:89:ab:cd:ef 852 // 01-23-45-67-89-ab 853 // 01-23-45-67-89-ab-cd-ef 854 // 0123.4567.89ab 855 // 0123.4567.89ab.cdef 856 func IsMAC[T ~string](str T) bool { 857 _, err := net.ParseMAC(string(str)) 858 return err == nil 859 } 860 861 // IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name 862 func IsHost[T ~string](str T) bool { 863 return IsIP(str) || IsDNSName(str) 864 } 865 866 // IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId. 867 func IsMongoID[T ~string](str T) bool { 868 return rxHexadecimal.MatchString(string(str)) && (len(str) == 24) 869 } 870 871 // IsLatitude checks if a string is valid latitude. 872 func IsLatitude[T ~string](str T) bool { 873 return rxLatitude.MatchString(string(str)) 874 } 875 876 // IsLongitude checks if a string is valid longitude. 877 func IsLongitude[T ~string](str T) bool { 878 return rxLongitude.MatchString(string(str)) 879 } 880 881 // IsIMEI checks if a string is valid IMEI 882 func IsIMEI[T ~string](str T) bool { 883 return rxIMEI.MatchString(string(str)) 884 } 885 886 // IsIMSI checks if a string is valid IMSI 887 func IsIMSI[T ~string](str T) bool { 888 if !rxIMSI.MatchString(string(str)) { 889 return false 890 } 891 892 mcc, err := strconv.ParseInt(string(str)[0:3], 10, 32) 893 if err != nil { 894 return false 895 } 896 897 switch mcc { 898 case 202, 204, 206, 208, 212, 213, 214, 216, 218, 219: 899 case 220, 221, 222, 226, 228, 230, 231, 232, 234, 235: 900 case 238, 240, 242, 244, 246, 247, 248, 250, 255, 257: 901 case 259, 260, 262, 266, 268, 270, 272, 274, 276, 278: 902 case 280, 282, 283, 284, 286, 288, 289, 290, 292, 293: 903 case 294, 295, 297, 302, 308, 310, 311, 312, 313, 314: 904 case 315, 316, 330, 332, 334, 338, 340, 342, 344, 346: 905 case 348, 350, 352, 354, 356, 358, 360, 362, 363, 364: 906 case 365, 366, 368, 370, 372, 374, 376, 400, 401, 402: 907 case 404, 405, 406, 410, 412, 413, 414, 415, 416, 417: 908 case 418, 419, 420, 421, 422, 424, 425, 426, 427, 428: 909 case 429, 430, 431, 432, 434, 436, 437, 438, 440, 441: 910 case 450, 452, 454, 455, 456, 457, 460, 461, 466, 467: 911 case 470, 472, 502, 505, 510, 514, 515, 520, 525, 528: 912 case 530, 536, 537, 539, 540, 541, 542, 543, 544, 545: 913 case 546, 547, 548, 549, 550, 551, 552, 553, 554, 555: 914 case 602, 603, 604, 605, 606, 607, 608, 609, 610, 611: 915 case 612, 613, 614, 615, 616, 617, 618, 619, 620, 621: 916 case 622, 623, 624, 625, 626, 627, 628, 629, 630, 631: 917 case 632, 633, 634, 635, 636, 637, 638, 639, 640, 641: 918 case 642, 643, 645, 646, 647, 648, 649, 650, 651, 652: 919 case 653, 654, 655, 657, 658, 659, 702, 704, 706, 708: 920 case 710, 712, 714, 716, 722, 724, 730, 732, 734, 736: 921 case 738, 740, 742, 744, 746, 748, 750, 995: 922 return true 923 default: 924 return false 925 } 926 return true 927 } 928 929 // IsRsaPublicKey checks if a string is valid public key with provided length 930 func IsRsaPublicKey[T ~string](str T, keylen int) bool { 931 bb := bytes.NewBufferString(string(str)) 932 pemBytes, err := ioutil.ReadAll(bb) 933 if err != nil { 934 return false 935 } 936 block, _ := pem.Decode(pemBytes) 937 if block != nil && block.Type != "PUBLIC KEY" { 938 return false 939 } 940 var der []byte 941 942 if block != nil { 943 der = block.Bytes 944 } else { 945 der, err = base64.StdEncoding.DecodeString(string(str)) 946 if err != nil { 947 return false 948 } 949 } 950 951 key, err := x509.ParsePKIXPublicKey(der) 952 if err != nil { 953 return false 954 } 955 pubkey, ok := key.(*rsa.PublicKey) 956 if !ok { 957 return false 958 } 959 bitlen := len(pubkey.N.Bytes()) * 8 960 return bitlen == int(keylen) 961 } 962 963 // IsRegex checks if a give string is a valid regex with RE2 syntax or not 964 func IsRegex[T ~string](str T) bool { 965 if _, err := regexp.Compile(string(str)); err == nil { 966 return true 967 } 968 return false 969 } 970 971 func toJSONName[T ~string](tag T) string { 972 if tag == "" { 973 return "" 974 } 975 976 // JSON name always comes first. If there's no options then split[0] is 977 // JSON name, if JSON name is not set, then split[0] is an empty string. 978 split := strings.SplitN(string(tag), ",", 2) 979 980 name := split[0] 981 982 // However it is possible that the field is skipped when 983 // (de-)serializing from/to JSON, in which case assume that there is no 984 // tag name to use 985 if name == "-" { 986 return "" 987 } 988 return name 989 } 990 991 func prependPathToErrors(err error, path string) error { 992 switch err2 := err.(type) { 993 case Error: 994 err2.Path = append([]string{path}, err2.Path...) 995 return err2 996 case Errors: 997 errors := err2.Errors() 998 for i, err3 := range errors { 999 errors[i] = prependPathToErrors(err3, path) 1000 } 1001 return err2 1002 } 1003 return err 1004 } 1005 1006 // ValidateArray performs validation according to condition iterator that validates every element of the array 1007 func ValidateArray[T any](array []T, iterator ConditionIterator[T]) bool { 1008 return Every[T](array, iterator) 1009 } 1010 1011 // ValidateMap use validation map for fields. 1012 // result will be equal to `false` if there are any errors. 1013 // s is the map containing the data to be validated. 1014 // m is the validation map in the form: 1015 // 1016 // map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}} 1017 func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error) { 1018 if s == nil { 1019 return true, nil 1020 } 1021 result := true 1022 var err error 1023 var errs Errors 1024 var index int 1025 val := reflect.ValueOf(s) 1026 for key, value := range s { 1027 presentResult := true 1028 validator, ok := m[key] 1029 if !ok { 1030 presentResult = false 1031 var err error 1032 err = fmt.Errorf("all map keys has to be present in the validation map; got %s", key) 1033 err = prependPathToErrors(err, key) 1034 errs = append(errs, err) 1035 } 1036 valueField := reflect.ValueOf(value) 1037 mapResult := true 1038 typeResult := true 1039 structResult := true 1040 resultField := true 1041 switch subValidator := validator.(type) { 1042 case map[string]interface{}: 1043 var err error 1044 if v, ok := value.(map[string]interface{}); !ok { 1045 mapResult = false 1046 err = fmt.Errorf("map validator has to be for the map type only; got %s", valueField.Type().String()) 1047 err = prependPathToErrors(err, key) 1048 errs = append(errs, err) 1049 } else { 1050 mapResult, err = ValidateMap(v, subValidator) 1051 if err != nil { 1052 mapResult = false 1053 err = prependPathToErrors(err, key) 1054 errs = append(errs, err) 1055 } 1056 } 1057 case string: 1058 if (valueField.Kind() == reflect.Struct || 1059 (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && 1060 subValidator != "-" { 1061 var err error 1062 structResult, err = ValidateStruct(valueField.Interface()) 1063 if err != nil { 1064 err = prependPathToErrors(err, key) 1065 errs = append(errs, err) 1066 } 1067 } 1068 resultField, err = typeCheck(valueField, reflect.StructField{ 1069 Name: key, 1070 PkgPath: "", 1071 Type: val.Type(), 1072 Tag: reflect.StructTag(fmt.Sprintf("%s:%q", tagName, subValidator)), 1073 Offset: 0, 1074 Index: []int{index}, 1075 Anonymous: false, 1076 }, val, nil) 1077 if err != nil { 1078 errs = append(errs, err) 1079 } 1080 case nil: 1081 // already handlerd when checked before 1082 default: 1083 typeResult = false 1084 err = fmt.Errorf("map validator has to be either map[string]interface{} or string; got %s", valueField.Type().String()) 1085 err = prependPathToErrors(err, key) 1086 errs = append(errs, err) 1087 } 1088 result = result && presentResult && typeResult && resultField && structResult && mapResult 1089 index++ 1090 } 1091 // checks required keys 1092 requiredResult := true 1093 for key, value := range m { 1094 if schema, ok := value.(string); ok { 1095 tags := parseTagIntoMap(schema) 1096 if required, ok := tags["required"]; ok { 1097 if _, ok := s[key]; !ok { 1098 requiredResult = false 1099 if required.customErrorMessage != "" { 1100 err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}} 1101 } else { 1102 err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}} 1103 } 1104 errs = append(errs, err) 1105 } 1106 } 1107 } 1108 } 1109 1110 if len(errs) > 0 { 1111 err = errs 1112 } 1113 return result && requiredResult, err 1114 } 1115 1116 // ValidateStruct use tags for fields. 1117 // result will be equal to `false` if there are any errors. 1118 // todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail) 1119 func ValidateStruct[T any](s T) (bool, error) { 1120 if reflect.ValueOf(s) == reflect.ValueOf(nil) { 1121 return true, nil 1122 } 1123 result := true 1124 var err error 1125 // we only accept structs 1126 val := reflect.ValueOf(s) 1127 if val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { 1128 val = val.Elem() 1129 } 1130 if val.Kind() != reflect.Struct { 1131 return false, fmt.Errorf("function only accepts structs; got %s", val.Kind()) 1132 } 1133 var errs Errors 1134 for i := 0; i < val.NumField(); i++ { 1135 valueField := val.Field(i) 1136 typeField := val.Type().Field(i) 1137 if typeField.PkgPath != "" { 1138 continue // Private field 1139 } 1140 structResult := true 1141 if valueField.Kind() == reflect.Interface { 1142 valueField = valueField.Elem() 1143 } 1144 if (valueField.Kind() == reflect.Struct || 1145 (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && 1146 typeField.Tag.Get(tagName) != "-" { 1147 var err error 1148 structResult, err = ValidateStruct(valueField.Interface()) 1149 if err != nil { 1150 err = prependPathToErrors(err, typeField.Name) 1151 errs = append(errs, err) 1152 } 1153 } 1154 resultField, err2 := typeCheck(valueField, typeField, val, nil) 1155 if err2 != nil { 1156 1157 // Replace structure name with JSON name if there is a tag on the variable 1158 jsonTag := toJSONName(typeField.Tag.Get("json")) 1159 if jsonTag != "" { 1160 switch jsonError := err2.(type) { 1161 case Error: 1162 jsonError.Name = jsonTag 1163 err2 = jsonError 1164 case Errors: 1165 for i2, err3 := range jsonError { 1166 switch customErr := err3.(type) { 1167 case Error: 1168 customErr.Name = jsonTag 1169 jsonError[i2] = customErr 1170 } 1171 } 1172 1173 err2 = jsonError 1174 } 1175 } 1176 1177 errs = append(errs, err2) 1178 } 1179 result = result && resultField && structResult 1180 } 1181 if len(errs) > 0 { 1182 err = errs 1183 } 1184 return result, err 1185 } 1186 1187 // ValidateStructAsync performs async validation of the struct and returns results through the channels 1188 func ValidateStructAsync[T any](s T) (<-chan bool, <-chan error) { 1189 res := make(chan bool) 1190 errors := make(chan error) 1191 1192 go func() { 1193 defer close(res) 1194 defer close(errors) 1195 1196 isValid, isFailed := ValidateStruct(s) 1197 1198 res <- isValid 1199 errors <- isFailed 1200 }() 1201 1202 return res, errors 1203 } 1204 1205 // ValidateMapAsync performs async validation of the map and returns results through the channels 1206 func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error) { 1207 res := make(chan bool) 1208 errors := make(chan error) 1209 1210 go func() { 1211 defer close(res) 1212 defer close(errors) 1213 1214 isValid, isFailed := ValidateMap(s, m) 1215 1216 res <- isValid 1217 errors <- isFailed 1218 }() 1219 1220 return res, errors 1221 } 1222 1223 // parseTagIntoMap parses a struct tag `valid:required~Some error message,length(2|3)` into map[string]string{"required": "Some error message", "length(2|3)": ""} 1224 func parseTagIntoMap(tag string) tagOptionsMap { 1225 optionsMap := make(tagOptionsMap) 1226 options := strings.Split(tag, ",") 1227 1228 for i, option := range options { 1229 option = strings.TrimSpace(option) 1230 1231 validationOptions := strings.Split(option, "~") 1232 if !isValidTag(validationOptions[0]) { 1233 continue 1234 } 1235 if len(validationOptions) == 2 { 1236 optionsMap[validationOptions[0]] = tagOption{validationOptions[0], validationOptions[1], i} 1237 } else { 1238 optionsMap[validationOptions[0]] = tagOption{validationOptions[0], "", i} 1239 } 1240 } 1241 return optionsMap 1242 } 1243 1244 func isValidTag(s string) bool { 1245 if s == "" { 1246 return false 1247 } 1248 for _, c := range s { 1249 switch { 1250 case strings.ContainsRune("\\'\"!#$%&()*+-./:<=>?@[]^_{|}~ ", c): 1251 // Backslash and quote chars are reserved, but 1252 // otherwise any punctuation chars are allowed 1253 // in a tag name. 1254 default: 1255 if !unicode.IsLetter(c) && !unicode.IsDigit(c) { 1256 return false 1257 } 1258 } 1259 } 1260 return true 1261 } 1262 1263 // IsSSN will validate the given string as a U.S. Social Security Number 1264 func IsSSN[T ~string](str T) bool { 1265 if str == "" || len(str) != 11 { 1266 return false 1267 } 1268 return rxSSN.MatchString(string(str)) 1269 } 1270 1271 // IsSemver checks if string is valid semantic version 1272 func IsSemver[T ~string](str T) bool { 1273 return rxSemver.MatchString(string(str)) 1274 } 1275 1276 // IsType checks if interface is of some type 1277 func IsType[T any](v T, params ...string) bool { 1278 if len(params) == 1 { 1279 typ := params[0] 1280 return strings.Replace(reflect.TypeOf(v).String(), " ", "", -1) == strings.Replace(typ, " ", "", -1) 1281 } 1282 return false 1283 } 1284 1285 // IsTime checks if string is valid according to given format 1286 func IsTime[T ~string](str T, format T) bool { 1287 _, err := time.Parse(string(format), string(str)) 1288 return err == nil 1289 } 1290 1291 // IsUnixTime checks if string is valid unix timestamp value 1292 func IsUnixTime[T ~string](str T) bool { 1293 if _, err := strconv.Atoi(string(str)); err == nil { 1294 return true 1295 } 1296 return false 1297 } 1298 1299 // IsRFC3339 checks if string is valid timestamp value according to RFC3339 1300 func IsRFC3339[T ~string](str T) bool { 1301 return IsTime(str, time.RFC3339) 1302 } 1303 1304 // IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone. 1305 func IsRFC3339WithoutZone[T ~string](str T) bool { 1306 return IsTime(str, rfc3339WithoutZone) 1307 } 1308 1309 // IsISO4217 checks if string is valid ISO currency code 1310 func IsISO4217[T ~string](str T) bool { 1311 for _, currency := range ISO4217List { 1312 if string(str) == currency { 1313 return true 1314 } 1315 } 1316 1317 return false 1318 } 1319 1320 // ByteLength checks string's length 1321 func ByteLength[T ~string](str T, params ...T) bool { 1322 if len(params) == 2 { 1323 min, _ := ToInt(params[0]) 1324 max, _ := ToInt(params[1]) 1325 return len(str) >= int(min) && len(str) <= int(max) 1326 } 1327 1328 return false 1329 } 1330 1331 // RuneLength checks string's length 1332 // Alias for StringLength 1333 func RuneLength[T ~string](str T, params ...string) bool { 1334 return StringLength(str, params...) 1335 } 1336 1337 // IsRsaPub checks whether string is valid RSA key 1338 // Alias for IsRsaPublicKey 1339 func IsRsaPub[T ~string](str T, params ...string) bool { 1340 if len(params) == 1 { 1341 lens, _ := ToInt(params[0]) 1342 return IsRsaPublicKey(str, int(lens)) 1343 } 1344 1345 return false 1346 } 1347 1348 // StringMatches checks if a string matches a given pattern. 1349 func StringMatches[T ~string](str T, params ...T) bool { 1350 if len(params) == 1 { 1351 pattern := params[0] 1352 return Matches(str, pattern) 1353 } 1354 return false 1355 } 1356 1357 // StringLength checks string's length (including multi byte strings) 1358 func StringLength[T ~string](str T, params ...string) bool { 1359 1360 if len(params) == 2 { 1361 strLength := utf8.RuneCountInString(string(str)) 1362 min, _ := ToInt(params[0]) 1363 max, _ := ToInt(params[1]) 1364 return strLength >= int(min) && strLength <= int(max) 1365 } 1366 1367 return false 1368 } 1369 1370 // MinStringLength checks string's minimum length (including multi byte strings) 1371 func MinStringLength[T ~string](str T, params ...T) bool { 1372 1373 if len(params) == 1 { 1374 strLength := utf8.RuneCountInString(string(str)) 1375 min, _ := ToInt(params[0]) 1376 return strLength >= int(min) 1377 } 1378 1379 return false 1380 } 1381 1382 // MaxStringLength checks string's maximum length (including multi byte strings) 1383 func MaxStringLength[T ~string](str T, params ...T) bool { 1384 1385 if len(params) == 1 { 1386 strLength := utf8.RuneCountInString(string(str)) 1387 max, _ := ToInt(params[0]) 1388 return strLength <= int(max) 1389 } 1390 1391 return false 1392 } 1393 1394 // Range checks string's length 1395 func Range[T ~string](str T, params ...T) bool { 1396 if len(params) == 2 { 1397 value, _ := ToNumber[T, float64](str) 1398 min, _ := ToNumber[T, float64](params[0]) 1399 max, _ := ToNumber[T, float64](params[1]) 1400 return InRange(value, min, max) 1401 } 1402 1403 return false 1404 } 1405 1406 // IsInRaw checks if string is in list of allowed values 1407 func IsInRaw[T ~string](str T, params ...T) bool { 1408 if len(params) == 1 { 1409 rawParams := params[0] 1410 1411 parsedParams := strings.Split(string(rawParams), "|") 1412 1413 return IsIn(str, parsedParams...) 1414 } 1415 1416 return false 1417 } 1418 1419 // IsIn checks if string str is a member of the set of strings params 1420 func IsIn[T ~string](str T, params ...string) bool { 1421 for _, param := range params { 1422 if string(str) == param { 1423 return true 1424 } 1425 } 1426 1427 return false 1428 } 1429 1430 func checkRequired(v reflect.Value, t reflect.StructField, options tagOptionsMap) (bool, error) { 1431 if nilPtrAllowedByRequired { 1432 k := v.Kind() 1433 if (k == reflect.Ptr || k == reflect.Interface) && v.IsNil() { 1434 return true, nil 1435 } 1436 } 1437 1438 if requiredOption, isRequired := options["required"]; isRequired { 1439 if len(requiredOption.customErrorMessage) > 0 { 1440 return false, Error{t.Name, fmt.Errorf(requiredOption.customErrorMessage), true, "required", []string{}} 1441 } 1442 return false, Error{t.Name, fmt.Errorf("non zero value required"), false, "required", []string{}} 1443 } else if _, isOptional := options["optional"]; fieldsRequiredByDefault && !isOptional { 1444 return false, Error{t.Name, fmt.Errorf("Missing required field"), false, "required", []string{}} 1445 } 1446 // not required and empty is valid 1447 return true, nil 1448 } 1449 1450 // revive:disable 1451 func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options tagOptionsMap) (isValid bool, resultErr error) { 1452 if !v.IsValid() { 1453 return false, nil 1454 } 1455 1456 tag := t.Tag.Get(tagName) 1457 1458 // checks if the field should be ignored 1459 switch tag { 1460 case "": 1461 if v.Kind() != reflect.Slice && v.Kind() != reflect.Map { 1462 if !fieldsRequiredByDefault { 1463 return true, nil 1464 } 1465 return false, Error{t.Name, fmt.Errorf("All fields are required to at least have one validation defined"), false, "required", []string{}} 1466 } 1467 case "-": 1468 return true, nil 1469 } 1470 1471 isRootType := false 1472 if options == nil { 1473 isRootType = true 1474 options = parseTagIntoMap(tag) 1475 } 1476 1477 if isEmptyValue(v) { 1478 // an empty value is not validated, checks only required 1479 isValid, resultErr = checkRequired(v, t, options) 1480 for key := range options { 1481 delete(options, key) 1482 } 1483 return isValid, resultErr 1484 } 1485 1486 var customTypeErrors Errors 1487 optionsOrder := options.orderedKeys() 1488 for _, validatorName := range optionsOrder { 1489 validatorStruct := options[validatorName] 1490 if validatefunc, ok := CustomTypeTagMap.Get(validatorName); ok { 1491 delete(options, validatorName) 1492 1493 if result := validatefunc(v.Interface(), o.Interface()); !result { 1494 if len(validatorStruct.customErrorMessage) > 0 { 1495 customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: TruncatingErrorf(validatorStruct.customErrorMessage, fmt.Sprint(v), validatorName), CustomErrorMessageExists: true, Validator: stripParams(validatorName)}) 1496 continue 1497 } 1498 customTypeErrors = append(customTypeErrors, Error{Name: t.Name, Err: fmt.Errorf("%s does not validate as %s", fmt.Sprint(v), validatorName), CustomErrorMessageExists: false, Validator: stripParams(validatorName)}) 1499 } 1500 } 1501 } 1502 1503 if len(customTypeErrors.Errors()) > 0 { 1504 return false, customTypeErrors 1505 } 1506 1507 if isRootType { 1508 // Ensure that we've checked the value by all specified validators before report that the value is valid 1509 defer func() { 1510 delete(options, "optional") 1511 delete(options, "required") 1512 1513 if isValid && resultErr == nil && len(options) != 0 { 1514 optionsOrder := options.orderedKeys() 1515 for _, validator := range optionsOrder { 1516 isValid = false 1517 resultErr = Error{t.Name, fmt.Errorf( 1518 "The following validator is invalid or can't be applied to the field: %q", validator), false, stripParams(validator), []string{}} 1519 return 1520 } 1521 } 1522 }() 1523 } 1524 1525 for _, validatorSpec := range optionsOrder { 1526 validatorStruct := options[validatorSpec] 1527 var negate bool 1528 validator := validatorSpec 1529 customMsgExists := len(validatorStruct.customErrorMessage) > 0 1530 1531 // checks whether the tag looks like '!something' or 'something' 1532 if validator[0] == '!' { 1533 validator = validator[1:] 1534 negate = true 1535 } 1536 1537 // checks for interface param validators 1538 for key, value := range InterfaceParamTagRegexMap { 1539 ps := value.FindStringSubmatch(validator) 1540 if len(ps) == 0 { 1541 continue 1542 } 1543 1544 validatefunc, ok := InterfaceParamTagMap[key] 1545 if !ok { 1546 continue 1547 } 1548 1549 delete(options, validatorSpec) 1550 1551 field := fmt.Sprint(v) 1552 if result := validatefunc(v, ps[1:]...); (!result && !negate) || (result && negate) { 1553 if customMsgExists { 1554 return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1555 } 1556 if negate { 1557 return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1558 } 1559 return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1560 } 1561 } 1562 } 1563 1564 switch v.Kind() { 1565 case reflect.Bool, 1566 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 1567 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, 1568 reflect.Float32, reflect.Float64, 1569 reflect.String: 1570 // for each tag option checks the map of validator functions 1571 for _, validatorSpec := range optionsOrder { 1572 validatorStruct := options[validatorSpec] 1573 var negate bool 1574 validator := validatorSpec 1575 customMsgExists := len(validatorStruct.customErrorMessage) > 0 1576 1577 // checks whether the tag looks like '!something' or 'something' 1578 if validator[0] == '!' { 1579 validator = validator[1:] 1580 negate = true 1581 } 1582 1583 // checks for param validators 1584 for key, value := range ParamTagRegexMap { 1585 ps := value.FindStringSubmatch(validator) 1586 if len(ps) == 0 { 1587 continue 1588 } 1589 1590 validatefunc, ok := ParamTagMap[key] 1591 if !ok { 1592 continue 1593 } 1594 1595 delete(options, validatorSpec) 1596 1597 switch v.Kind() { 1598 case reflect.String, 1599 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 1600 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, 1601 reflect.Float32, reflect.Float64: 1602 1603 field := fmt.Sprint(v) // make value into string, then validate with regex 1604 if result := validatefunc(field, ps[1:]...); (!result && !negate) || (result && negate) { 1605 if customMsgExists { 1606 return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1607 } 1608 if negate { 1609 return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1610 } 1611 return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1612 } 1613 default: 1614 // type not yet supported, fail 1615 return false, Error{t.Name, fmt.Errorf("Validator %s doesn't support kind %s", validator, v.Kind()), false, stripParams(validatorSpec), []string{}} 1616 } 1617 } 1618 1619 if validatefunc, ok := TagMap[validator]; ok { 1620 delete(options, validatorSpec) 1621 1622 switch v.Kind() { 1623 case reflect.String, 1624 reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, 1625 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, 1626 reflect.Float32, reflect.Float64: 1627 field := fmt.Sprint(v) // make value into string, then validate with regex 1628 if result := validatefunc(field); !result && !negate || result && negate { 1629 if customMsgExists { 1630 return false, Error{t.Name, TruncatingErrorf(validatorStruct.customErrorMessage, field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1631 } 1632 if negate { 1633 return false, Error{t.Name, fmt.Errorf("%s does validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1634 } 1635 return false, Error{t.Name, fmt.Errorf("%s does not validate as %s", field, validator), customMsgExists, stripParams(validatorSpec), []string{}} 1636 } 1637 default: 1638 // Not Yet Supported Types (Fail here!) 1639 err := fmt.Errorf("Validator %s doesn't support kind %s for value %v", validator, v.Kind(), v) 1640 return false, Error{t.Name, err, false, stripParams(validatorSpec), []string{}} 1641 } 1642 } 1643 } 1644 return true, nil 1645 case reflect.Map: 1646 if v.Type().Key().Kind() != reflect.String { 1647 return false, &UnsupportedTypeError{v.Type()} 1648 } 1649 var sv stringValues 1650 sv = v.MapKeys() 1651 sort.Sort(sv) 1652 result := true 1653 for i, k := range sv { 1654 var resultItem bool 1655 var err error 1656 if v.MapIndex(k).Kind() != reflect.Struct { 1657 resultItem, err = typeCheck(v.MapIndex(k), t, o, options) 1658 if err != nil { 1659 return false, err 1660 } 1661 } else { 1662 resultItem, err = ValidateStruct(v.MapIndex(k).Interface()) 1663 if err != nil { 1664 err = prependPathToErrors(err, t.Name+"."+sv[i].Interface().(string)) 1665 return false, err 1666 } 1667 } 1668 result = result && resultItem 1669 } 1670 return result, nil 1671 case reflect.Slice, reflect.Array: 1672 result := true 1673 for i := 0; i < v.Len(); i++ { 1674 var resultItem bool 1675 var err error 1676 if v.Index(i).Kind() != reflect.Struct { 1677 resultItem, err = typeCheck(v.Index(i), t, o, options) 1678 if err != nil { 1679 return false, err 1680 } 1681 } else { 1682 resultItem, err = ValidateStruct(v.Index(i).Interface()) 1683 if err != nil { 1684 err = prependPathToErrors(err, t.Name+"."+strconv.Itoa(i)) 1685 return false, err 1686 } 1687 } 1688 result = result && resultItem 1689 } 1690 return result, nil 1691 case reflect.Interface: 1692 // If the value is an interface then encode its element 1693 if v.IsNil() { 1694 return true, nil 1695 } 1696 return ValidateStruct(v.Interface()) 1697 case reflect.Ptr: 1698 // If the value is a pointer then checks its element 1699 if v.IsNil() { 1700 return true, nil 1701 } 1702 return typeCheck(v.Elem(), t, o, options) 1703 case reflect.Struct: 1704 return true, nil 1705 default: 1706 return false, &UnsupportedTypeError{v.Type()} 1707 } 1708 } 1709 1710 func stripParams(validatorString string) string { 1711 return paramsRegexp.ReplaceAllString(validatorString, "") 1712 } 1713 1714 // isEmptyValue checks whether value empty or not 1715 func isEmptyValue(v reflect.Value) bool { 1716 switch v.Kind() { 1717 case reflect.String, reflect.Array: 1718 return v.Len() == 0 1719 case reflect.Map, reflect.Slice: 1720 return v.Len() == 0 || v.IsNil() 1721 case reflect.Bool: 1722 return !v.Bool() 1723 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: 1724 return v.Int() == 0 1725 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: 1726 return v.Uint() == 0 1727 case reflect.Float32, reflect.Float64: 1728 return v.Float() == 0 1729 case reflect.Interface, reflect.Ptr: 1730 return v.IsNil() 1731 } 1732 1733 return reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) 1734 } 1735 1736 // ErrorByField returns error for specified field of the struct 1737 // validated by ValidateStruct or empty string if there are no errors 1738 // or this field doesn't exists or doesn't have any errors. 1739 func ErrorByField(e error, field string) string { 1740 if e == nil { 1741 return "" 1742 } 1743 return ErrorsByField(e)[field] 1744 } 1745 1746 // ErrorsByField returns map of errors of the struct validated 1747 // by ValidateStruct or empty map if there are no errors. 1748 func ErrorsByField(e error) map[string]string { 1749 m := make(map[string]string) 1750 if e == nil { 1751 return m 1752 } 1753 // prototype for ValidateStruct 1754 1755 switch e := e.(type) { 1756 case Error: 1757 m[e.Name] = e.Err.Error() 1758 case Errors: 1759 for _, item := range e.Errors() { 1760 n := ErrorsByField(item) 1761 for k, v := range n { 1762 m[k] = v 1763 } 1764 } 1765 } 1766 1767 return m 1768 } 1769 1770 // Error returns string equivalent for reflect.Type 1771 func (e *UnsupportedTypeError) Error() string { 1772 return "validator: unsupported type: " + e.Type.String() 1773 } 1774 1775 func (sv stringValues) Len() int { return len(sv) } 1776 1777 func (sv stringValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } 1778 1779 func (sv stringValues) Less(i, j int) bool { return sv.get(i) < sv.get(j) } 1780 1781 func (sv stringValues) get(i int) string { return sv[i].String() } 1782 1783 func IsE164[T ~string](str T) bool { 1784 return rxE164.MatchString(string(str)) 1785 }