package utils import ( "fmt" "strconv" "time" ) func IsValidOldIDCard(idCard string) bool { if len(idCard) != 15 { return false } // 分离出生日期 birthYearStr := idCard[6:8] birthMonthStr := idCard[8:10] birthDayStr := idCard[10:12] // 转换为四位年份 birthYear, err := strconv.Atoi(birthYearStr) if err != nil { return false } if birthYear >= 0 && birthYear <= 99 { birthYear = 1900 + birthYear } else if birthYear >= 100 && birthYear <= 999 { birthYear = 2000 + (birthYear % 100) } birthMonth, err := strconv.Atoi(birthMonthStr) if err != nil { return false } birthDay, err := strconv.Atoi(birthDayStr) if err != nil { return false } // 检查出生日期是否有效 if birthYear < 1900 || birthYear > time.Now().Year() || birthMonth < 1 || birthMonth > 12 || birthDay < 1 || birthDay > 31 { return false } // 检查月份和天数的有效性 _, err = time.Parse(time.DateOnly, fmt.Sprintf("%d-%d-%d", birthYear, birthMonth, birthDay)) if err != nil { return false } // 检查性别 genderCode, _ := strconv.Atoi(idCard[14:15]) if genderCode%2 == 0 { return true // 女性 } else { return true // 男性 } } func IsValidIDCard(idCard string) bool { if len(idCard) != 18 { return false } // 加权因子 weights := []int{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2} // 校验码映射表 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"} // 计算校验码 sum := 0 for i, ch := range idCard[:17] { digit, _ := strconv.Atoi(string(ch)) sum += digit * weights[i] } checkSum := sum % 11 checkDigit := checkSumMap[checkSum] check := idCard[17:18] // 检查最后一位是否匹配 if checkDigit != check { return false } // 验证出生日期 birthYear, _ := strconv.Atoi(idCard[6:10]) birthMonth, _ := strconv.Atoi(idCard[10:12]) birthDay, _ := strconv.Atoi(idCard[12:14]) if birthYear < 1900 || birthYear > time.Now().Year() || birthMonth < 1 || birthMonth > 12 || birthDay < 1 || birthDay > 31 { return false } // 检查月份和天数的有效性 _, err := time.Parse(time.DateOnly, fmt.Sprintf("%d-%d-%d", birthYear, birthMonth, birthDay)) if err != nil { return false } // 检查性别 genderCode, _ := strconv.Atoi(idCard[16:17]) if genderCode%2 == 0 { return true // 女性 } else { return true // 男性 } }