验证身份证号是否符合规则,比较实用,错判率我自己测试为0,挺好用的,欢迎大神补充。
protected bool checkidcard(string idcard) { //验证18位或者17位加大小写x Regex rg = new Regex(@"^\d{17}(\d|X|x)$"); Match mc = rg.Match(idcard); string r = ""; if (!mc.Success) return false; //验证前两位是否符合地区代码 string[] area = { "11", "12", "13", "14", "15", "21", "22", "23", "31", "32", "33", "34", "35", "36", "37", "41", "42", "43", "44", "45", "46", "50", "51", "52", "53", "54", "61", "62", "63", "64", "65", "71", "81", "82", "91" }; bool b = false; foreach(string a in area) { if (idcard.Substring(0, 2) == a) { b = true; break; } } if (b == false) return false; //验证出生日期 string birthday = idcard.Substring(6, 4) + "/" + idcard.Substring(10, 2) + "/" + idcard.Substring(12, 2); try { Convert.ToDateTime(birthday); } catch { return false; } //验证最后一位校验位是否符合规则 int i = (int.Parse(idcard.Substring(0, 1)) * 7) + (int.Parse(idcard.Substring(1, 1)) * 9) + (int.Parse(idcard.Substring(2, 1)) * 10) + (int.Parse(idcard.Substring(3, 1)) * 5) + (int.Parse(idcard.Substring(4, 1)) * 8) + (int.Parse(idcard.Substring(5, 1)) * 4) + (int.Parse(idcard.Substring(6, 1)) * 2) + (int.Parse(idcard.Substring(7, 1)) * 1) + (int.Parse(idcard.Substring(8, 1)) * 6) + (int.Parse(idcard.Substring(9, 1)) * 3) + (int.Parse(idcard.Substring(10, 1)) * 7) + (int.Parse(idcard.Substring(11, 1)) * 9) + (int.Parse(idcard.Substring(12, 1)) * 10) + (int.Parse(idcard.Substring(13, 1)) * 5) + (int.Parse(idcard.Substring(14, 1)) * 8) + (int.Parse(idcard.Substring(15, 1)) * 4) + (int.Parse(idcard.Substring(16, 1)) * 2); i = i - i / 11 * 11; switch (i) { case 0: r = "1"; break; case 1: r = "0"; break; case 2: r = "11"; break; case 3: r = "9"; break; case 4: r = "8"; break; case 5: r = "7"; break; case 6: r = "6"; break; case 7: r = "5"; break; case 8: r = "4"; break; case 9: r = "3"; break; case 10: r = "2"; break; } if (r == "11") r = "x"; if (r == idcard.ToLower().Substring(17, 1)) return true; else return false; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/hr541659660/article/details/47811891