中国身份证号(18位)前六位为行政区域代码, 中间八位为出生日期, 再后三位为顺序码, 偶数分配给女性, 奇数给男性, 最后一位为校验位, 值为身份证前十七位加权求和,然后对11取模,进行映射。
权值为 [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
映射为 [“1”, “0”, “X”, “9”, “8”, “7”, “6”, “5”, “4”, “3”, “2”]
C#代码如下:
public static class StringHelper
{
/// <summary>
/// 验证是否合法的中国身份证号码(18位)
/// </summary>
/// <param name="identityNumber">身份证号</param>
/// <returns></returns>
public static bool IdentityNumberVerification(this string identityNumber)
{
// 字符串长度验证
if (identityNumber.Length != 18)
{
return false;
}
// 基本格式验证
if (long.TryParse(identityNumber.Remove(17), out long n) == false || n < Math.Pow(10, 16) || long.TryParse(identityNumber.Replace('x', '0').Replace('X', '0'), out _) == false)
{
return false;
}
// 省份码验证
string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";
if (address.IndexOf(identityNumber.Remove(2)) == -1)
{
return false;
}
// 生日验证
string birth = identityNumber.Substring(6, 8).Insert(6, "-").Insert(4, "-");
if (DateTime.TryParse(birth, out _) == 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 = identityNumber.Remove(17).ToCharArray();
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());
}
int re = sum % 11;
if (arrVarifyCode[re] != identityNumber.Substring(17, 1).ToLower())
{
return false;
}
// 以上所有验证通过,证明是符合GB11643-1999标准的身份证号
return true;
}
}
微信扫描二维码
在手机上观看本页