Lua身份证号校验
--返回狀態標識
local status = {success = 0,error_length = 1,error_format = 2,error_address = 3,error_birthday = 4,error_code = 5,
}--身份證長度
local idLength = 18--有效省級地址碼
local provinceCode = {11, 12, 13, 14, 15,21, 22, 23,31, 32, 33, 34, 35, 36, 37, 71,41, 42, 43,44, 45, 46, 81, 82,51, 52, 53, 54, 50,61, 62, 63, 64, 65
}--校驗碼(身份證最后一位)根據前面十七位數字碼,按照ISO7064:1983.MOD11-2校驗碼計算出來的校驗碼。
local checkCode = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}
local mappedCode = {"1", "0", "x", "9", "8", "7", "6", "5", "4", "3", "2"}--長度檢測
function isLengthOk(id)if #id ~= idLength thenreturn falseelsereturn trueend
end--格式檢測
function isFormatOk(id)if string.match(id, "%d+") == id or string.match(id, "%d+x") == id thenreturn trueelsereturn falseend
end--地址檢測
function isAddressOk(id)--省local province = tonumber(id:sub(1,2))local isProvinceOk = falsefor _,v in ipairs(provinceCode) doif province == v thenisProvinceOk = truebreakendend--市local city = tonumber(id:sub(3,4))local isCityOk = falseif city >= 1 and city <= 70 thenisCityOk = trueend--縣local county = tonumber(id:sub(5,6))local isCountyOk = falseif (county >= 1 and county <= 18) or (county >= 21 and county <= 99) thenisCountyOk = trueendif isProvinceOk and isCityOk and isCountyOk thenreturn trueelsereturn falseend
end--出生日期檢測
function isBirthdayOk(id)local y = tonumber(id:sub(7,10))local m = tonumber(id:sub(11,12))local d = tonumber(id:sub(13,14))local date = {year = y, month = m, day = d}local t = os.time(date)local revertDate = os.date("*t",t)if revertDate.year == date.year and revertDate.month == date.month and revertDate.day == date.day thenreturn trueelsereturn falseend
end--校驗碼檢測
function isCheckCodeOk(id)local preId = id:sub(1,17)local nums = {}for c in preId:gmatch(".") dotable.insert(nums,tonumber(c))endlocal sum = 0for i,v in ipairs(nums) dosum = sum + v * checkCode[i]endif mappedCode[(sum%11+1)] == id:sub(18, 18) thenreturn trueelsereturn falseend
end--身份證校驗
function verifyID(id)if not isLengthOk(id) thenreturn status.error_lengthendif not isFormatOk(id) thenreturn status.error_formatendif not isAddressOk(id) thenreturn status.error_addressendif not isBirthdayOk(id) thenreturn status.error_birthdayendif not isCheckCodeOk(id) thenreturn status.error_codeendreturn status.success
end
總結
- 上一篇: ExtJs学习笔记——Ext.grid.
- 下一篇: IDEA 集成配置 Jad