common_utils.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. package utils
  2. import (
  3. "fmt"
  4. "strconv"
  5. "time"
  6. )
  7. func IsValidOldIDCard(idCard string) bool {
  8. if len(idCard) != 15 {
  9. return false
  10. }
  11. // 分离出生日期
  12. birthYearStr := idCard[6:8]
  13. birthMonthStr := idCard[8:10]
  14. birthDayStr := idCard[10:12]
  15. // 转换为四位年份
  16. birthYear, err := strconv.Atoi(birthYearStr)
  17. if err != nil {
  18. return false
  19. }
  20. if birthYear >= 0 && birthYear <= 99 {
  21. birthYear = 1900 + birthYear
  22. } else if birthYear >= 100 && birthYear <= 999 {
  23. birthYear = 2000 + (birthYear % 100)
  24. }
  25. birthMonth, err := strconv.Atoi(birthMonthStr)
  26. if err != nil {
  27. return false
  28. }
  29. birthDay, err := strconv.Atoi(birthDayStr)
  30. if err != nil {
  31. return false
  32. }
  33. // 检查出生日期是否有效
  34. if birthYear < 1900 || birthYear > time.Now().Year() ||
  35. birthMonth < 1 || birthMonth > 12 ||
  36. birthDay < 1 || birthDay > 31 {
  37. return false
  38. }
  39. // 检查月份和天数的有效性
  40. _, err = time.Parse(time.DateOnly, fmt.Sprintf("%d-%d-%d", birthYear, birthMonth, birthDay))
  41. if err != nil {
  42. return false
  43. }
  44. // 检查性别
  45. genderCode, _ := strconv.Atoi(idCard[14:15])
  46. if genderCode%2 == 0 {
  47. return true // 女性
  48. } else {
  49. return true // 男性
  50. }
  51. }
  52. func IsValidIDCard(idCard string) bool {
  53. if len(idCard) != 18 {
  54. return false
  55. }
  56. // 加权因子
  57. weights := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
  58. // 校验码映射表
  59. checkSumMap := map[int]string{0: "1", 1: "0", 2: "X", 3: "9", 4: "8", 5: "7", 6: "6", 7: "5", 8: "4", 9: "3", 10: "2"}
  60. // 计算校验码
  61. sum := 0
  62. for i, ch := range idCard[:17] {
  63. digit, _ := strconv.Atoi(string(ch))
  64. sum += digit * weights[i]
  65. }
  66. checkSum := sum % 11
  67. checkDigit := checkSumMap[checkSum]
  68. check := idCard[17:18]
  69. // 检查最后一位是否匹配
  70. if checkDigit != check {
  71. return false
  72. }
  73. // 验证出生日期
  74. birthYear, _ := strconv.Atoi(idCard[6:10])
  75. birthMonth, _ := strconv.Atoi(idCard[10:12])
  76. birthDay, _ := strconv.Atoi(idCard[12:14])
  77. if birthYear < 1900 || birthYear > time.Now().Year() ||
  78. birthMonth < 1 || birthMonth > 12 ||
  79. birthDay < 1 || birthDay > 31 {
  80. return false
  81. }
  82. // 检查月份和天数的有效性
  83. _, err := time.Parse(time.DateOnly, fmt.Sprintf("%d-%d-%d", birthYear, birthMonth, birthDay))
  84. if err != nil {
  85. return false
  86. }
  87. // 检查性别
  88. genderCode, _ := strconv.Atoi(idCard[16:17])
  89. if genderCode%2 == 0 {
  90. return true // 女性
  91. } else {
  92. return true // 男性
  93. }
  94. }