You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

95 lines
2.0 KiB

  1. package idvalidator
  2. import (
  3. "errors"
  4. "regexp"
  5. "strconv"
  6. "strings"
  7. "time"
  8. )
  9. // 检查ID参数
  10. func checkIdArgument(id string) bool {
  11. _, err := generateCode(id)
  12. return err == nil
  13. }
  14. // 生成数据
  15. func generateCode(id string) (map[string]string, error) {
  16. length := len(id)
  17. if length == 15 {
  18. return generateShortCode(id)
  19. }
  20. if length == 18 {
  21. return generateLongCode(id)
  22. }
  23. return map[string]string{}, errors.New("Invalid ID card number length.")
  24. }
  25. // 生成短数据
  26. func generateShortCode(id string) (map[string]string, error) {
  27. if len(id) != 15 {
  28. return map[string]string{}, errors.New("Invalid ID card number length.")
  29. }
  30. mustCompile := regexp.MustCompile("(.{6})(.{6})(.{3})")
  31. subMatch := mustCompile.FindStringSubmatch(strings.ToLower(id))
  32. return map[string]string{
  33. "body": subMatch[0],
  34. "addressCode": subMatch[1],
  35. "birthdayCode": "19" + subMatch[2],
  36. "order": subMatch[3],
  37. "checkBit": "",
  38. "type": "15",
  39. }, nil
  40. }
  41. // 生成长数据
  42. func generateLongCode(id string) (map[string]string, error) {
  43. if len(id) != 18 {
  44. return map[string]string{}, errors.New("Invalid ID card number length.")
  45. }
  46. mustCompile := regexp.MustCompile("((.{6})(.{8})(.{3}))(.)")
  47. subMatch := mustCompile.FindStringSubmatch(strings.ToLower(id))
  48. return map[string]string{
  49. "body": subMatch[1],
  50. "addressCode": subMatch[2],
  51. "birthdayCode": subMatch[3],
  52. "order": subMatch[4],
  53. "checkBit": subMatch[5],
  54. "type": "18",
  55. }, nil
  56. }
  57. // 检查地址码
  58. func checkAddressCode(addressCode string, birthdayCode string) bool {
  59. return getAddressInfo(addressCode, birthdayCode)["province"] != ""
  60. }
  61. // 检查出生日期码
  62. func checkBirthdayCode(birthdayCode string) bool {
  63. year, _ := strconv.Atoi(substr(birthdayCode, 0, 4))
  64. if year < 1800 {
  65. return false
  66. }
  67. nowYear := time.Now().Year()
  68. if year > nowYear {
  69. return false
  70. }
  71. _, err := time.Parse("20060102", birthdayCode)
  72. return err == nil
  73. }
  74. // 检查顺序码
  75. func checkOrderCode(orderCode string) bool {
  76. return len(orderCode) == 3
  77. }