Skip to content

Instantly share code, notes, and snippets.

@vincascm
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save vincascm/c8f2d019b7b3c3b3e45d to your computer and use it in GitHub Desktop.

Select an option

Save vincascm/c8f2d019b7b3c3b3e45d to your computer and use it in GitHub Desktop.
18位国内身份证号码验证
function check (id)
local error_code = { "The length of ID card number is not 18.", "ID card number is invalid.",
"birthday is invalid.", "check code is invalid." }
local month_day = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }
local weight = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 }
local check_code = { "1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2" }
local year = tonumber(string.sub(id, 7, 10))
local month = tonumber(string.sub(id, 11, 12))
local day = tonumber(string.sub(id, 13, 14))
local sum = 0
-- verify length
if string.len(id) ~= 18 then
return error_code[1]
end
-- verify sign
if not(tonumber(string.sub(id,1,6)) and year and month and day and string.match(string.sub(id,18), "[%dXx]")) then
return error_code[2]
end
-- verify birthday
if (year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0 then month_day[2] = month_day[2] + 1 end
if not ( year < 4000 and year > 1800 and month <= 12 and month > 0 and day <= month_day[month] and day > 0) then
return error_code[3]
end
-- verify last bit which is check code
for k, v in ipairs(weight) do
sum = sum + string.sub(id,k,k) * v
end
if string.upper(string.sub(id, 18)) ~= check_code[sum % 11 + 1] then
return error_code[4]
end
return false
end
info = check("123456199001023824")
if info then
print(info)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment