C#验证身份证号码正确性的实例代码(收藏)
程序员文章站
2023-12-14 19:07:40
今天在qq空间看到一篇关于c#语言验证18位身份证号码的验证方法和实例代码,抽了些时间学习了一下,个人觉得还不错,所以把它记了下来,方便以后使用!
18位号码:...
今天在qq空间看到一篇关于c#语言验证18位身份证号码的验证方法和实例代码,抽了些时间学习了一下,个人觉得还不错,所以把它记了下来,方便以后使用!
18位号码:
private static bool checkidcard18(string id) { long n = 0; if (long.tryparse(id.remove(17), out n) == false || n < math.pow(10, 16) || long.tryparse(id.replace('x', '0').replace('x', '0'), out n) == false) { return false; } string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; if (address.indexof(id.remove(2)) == -1) { return false; } string birth = id.substring(6, 8).insert(6, "-").insert(4, "-"); datetime time = new datetime(); if (datetime.tryparse(birth, out time) == false) { return false; } string[] arrvarifycode = ("1,0,x,9,8,7,6,5,4,3,2").split(','); string[] wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").split(','); char[] ai = id.remove(17).tochararray(); int sum = 0; for (int i = 0; i < 17; i++) { sum += int.parse(wi[i]) * int.parse(ai[i].tostring()); } int y = -1; math.divrem(sum, 11, out y); if (arrvarifycode[y] != id.substring(17, 1).tolower()) { return false; } return true;//正确 }
15位号码:
private static bool checkidcard15(string id) { long n = 0; if (long.tryparse(id, out n) == false || n < math.pow(10, 14)) { return false; } string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91"; if (address.indexof(id.remove(2)) == -1) { return false; } string birth = id.substring(6, 6).insert(4, "-").insert(2, "-"); datetime time = new datetime(); if (datetime.tryparse(birth, out time) == false) { return false; } return true;//正确 }
总结
以上所述是小编给大家介绍的c#验证身份证号码是否正确,希望对大家有所帮助