身份证验证算法
using System;
using System.Collections.Generic; using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace IDCard
{
public partial class FrmIDC : Form
{
public FrmIDC()
{
InitializeComponent();
}
private void btnCheck_Click(object sender, EventArgs e)
{
IdCheckResult icr = CheckIDCard(txtIDC.Text.Trim());
switch (icr)
{
case IdCheckResult.ChrError:
lblTitle.Text = "你输入的身份证号码含有非法字符~";
txtIDC.Focus();
break;
case IdCheckResult.NotInCh:
lblTitle.Text = "你输入的身份证不再中国境内~";
txtIDC.Focus();
break;
case IdCheckResult.BirthError:
lblTitle.Text = "你输入的身份证生日部分非法~";
txtIDC.Focus();
break;
case IdCheckResult.CheckFalse:
lblTitle.Text = "你输入的身份证号码不合法~";
txtIDC.Focus();
break;
case IdCheckResult.Success:
break;
default:
break;
}
}
public enum IdCheckResult
{
ChrError, NotInCh, BirthError, CheckFalse, Success
}
private IdCheckResult CheckIDCard(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 IdCheckResult.ChrError;
}
string address =
"11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x3
4x43x52x64x65x71x81x82x91";
if (address.IndexOf(id.Remove(2)) == -1)
{
return IdCheckResult.NotInCh;
}
string birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
DateTime time = new DateTime();
if (DateTime.TryParse(birth, out time) == false)
{
return IdCheckResult.BirthError;
}
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))
{
return IdCheckResult.CheckFalse;
}
if (int.Parse(id.Substring(16, 1)) % 2 == 0)
{
txtSex.Text = "女";
}
else
{
txtSex.Text = "男 ";
}
txtBirth.Text = birth.ToString();
txtAddress.Text = address.Substring(address.IndexOf(id.Remove(2)),
2).ToString();
return IdCheckResult.Success;
}
}
}