一段简单的身份证校验代码,由身份证的前17位计算第18位是否合法,作为处理身份证号的第一步。
具体算法参看:百度百科
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace IdCard
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private bool CheckId(string id) {
int[] wQuan={7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
string checkWei = "10X98765432";
string number17 = id.Substring(0, 17);
string number18 = id.Substring(17);
int sum=0;
for (int i = 0; i < 17; i++) {
sum+=Convert.ToInt32(number17[i].ToString()) * wQuan[i];
}
int mod = sum % 11;
string result = checkWei[mod].ToString();
return (number18.Equals(result, StringComparison.OrdinalIgnoreCase));
}
private void button1_Click(object sender, EventArgs e)
{
string id = txtId.Text.Trim();
if (id.Length == 18) {
if (this.CheckId(id))
{
MessageBox.Show("合法");
}
else {
MessageBox.Show("不合法");
}
}
else
{
MessageBox.Show("身份证号码输入有误!");
return;
}
}
private void txtId_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9') {
e.Handled = true;
//阻止数字以外字符
}
if ((txtId.SelectionStart == 17)&& (e.KeyChar == 'x' || e.KeyChar == 'X')) {
e.Handled = false;
//允许第18位为x/X
}
if (e.KeyChar == 8)
{
e.Handled = false;
//允许backspace输入
}
}
}
}