身份证号码验证 python
时间: 2025-05-14 15:16:51 浏览: 23
### Python 实现身份证号码验证
对于中国居民身份证号码的验证,主要依据GB11643-1999标准。此标准规定了身份证号码由18位组成,其中前17位为信息码,最后一位是校验码[^1]。
#### 验证逻辑概述
1. **长度检查**
- 身份证号码应严格为18位字符。
2. **区域编码合法性**
- 前两位代表省份代码,需确认其属于合法范围内。
3. **出生日期有效性**
- 中间六位表示年月日(YYYYMMDD),要确保这些数值构成合理的时间戳。
4. **性别与顺序码**
- 第十七位决定了持证人性别以及排列序号奇偶性。
5. **校验码计算**
- 使用加权求和再取模的方式得出最终的检验位,并对比实际提供的第十八位是否相符。
以下是具体的Python实现:
```python
import re
from datetime import datetime
def validate_id_number(id_num):
"""
Validate Chinese ID number.
Args:
id_num (str): The inputted ID string to be validated.
Returns:
str: Error message or 'Validation passed!'
"""
# 定义错误提示列表
errors = ['验证通过!', '身份证号码位数不对!', '身份证号码出生日期超出范围或含有非法字符!',
'身份证号码校验错误!', '身份证地区非法!']
# 正则表达式初步过滤非数字字母组合
if not re.match(r'^\d{17}[\dxX]$', id_num):
return errors[1]
try:
birth_date = int(id_num[6:14])
datetime.strptime(str(birth_date), '%Y%m%d')
except ValueError:
return errors[2]
weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
check_digits = {'0': '1', '1': '0', '2': 'X', '3': '9', '4': '8',
'5': '7', '6': '6', '7': '5', '8': '4', '9': '3'}
sum_of_products = sum([int(a)*b for a, b in zip(list(id_num[:-1]), weights)])
mod_result = str(sum_of_products % 11)
expected_check_digit = check_digits.get(mod_result.upper(), '')
if id_num[-1].upper() != expected_check_digit:
return errors[3]
provinces = set(['11', '12', '13', ...]) # 省级行政区划代码集合简化版
province_code = id_num[:2]
if province_code not in provinces:
return errors[4]
return errors[0]
if __name__ == '__main__':
test_ids = ["123456789012345678", "123456199001011234"]
results = {id_: validate_id_number(id_) for id_ in test_ids}
print(results)
```
上述代码实现了完整的身份证号码验证流程,包括但不限于格式匹配、日期解析、权重乘积累加及余数映射表对照等操作来完成对给定字符串的有效性评估[^2].
阅读全文
相关推荐

















