python身份證校驗

2021-09-25 22:37:59 字數 1757 閱讀 3155

驗證規則如下: 

長度必須為18位; 

格式為:前17位是數字,最後一位是數字或者x(不區分大小寫); 

前6位是地區碼,必須存在; 

第7位到12位是出生日期,必須是存在的日期; 

最後一位是驗證位,規則必須匹配;

輸入為乙個身份證號的字串; 

輸出為乙個tuple: 

0 - 是否是身份證; 

1 - 錯誤資訊或者所屬地區;

import re

import datetime

def isidcard(id_number):

area_dict =

id_code_list = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]

check_code_list = [1, 0, 'x', 9, 8, 7, 6, 5, 4, 3, 2]

if len(id_number) != 18:

return false, "length error"

if not re.match(r"^\d(\d|x|x)$", id_number):

return false, "format error"

if id_number[0:6] not in area_dict:

return false, "area code error"

try:

datetime.date(int(id_number[6:10]), int(id_number[10:12]), int(id_number[12:14]))

except valueerror as ve:

return false, "datetime error: ".format(ve)

if str(check_code_list[sum([a * b for a, b in zip(id_code_list, [int(a) for a in id_number[0:-1]])]) % 11]) != \

str(id_number.upper()[-1]):

return false, "check code error"

return true, "{}省 {}市 {}".format(area_dict[id_number[0:2] + "0000"].rstrip("省"),

area_dict[id_number[0:4] + "00"].rstrip("市"),

area_dict[id_number[0:6]])

if __name__ == "__main__":

print(isidcard("330702196302260412x"))

print(isidcard("3307021963x226041x"))

print(isidcard("330702196hehe41x"))

print(isidcard("39070219630226041x"))

print(isidcard("33070219630229041x"))

print(isidcard("330702196302260410"))

print(isidcard("33070219630226041x"))

print(isidcard("33070219630226041x"))

結果:

身份證校驗

int isright string card cout 9 wi sum 11 if p 17 x p 17 x 最後一位為 x 或 x else if id wi p 17 判斷計算出的身份證校驗碼與輸入是否相符 return error 判斷身份證號碼中的年月日是否正確 bool birthd...

身份證校驗

const regexutils else 手機號碼格式驗證 checkmobile mobile string boolean return regex.test mobile.trim else 郵箱格式驗證 checkemail email string boolean result rege...

js校驗身份證

begin 校驗身份證 function checkidcard formname,inputname,itemname var area alert area parseint idcard.substr 0,2 var y,jym var s,m var idcard array new arr...