C#实现身份证验证功能的示例代码

.NET
258
0
0
2023-07-07
标签   C#
目录
  • 实践过程
  • 效果
  • 代码

实践过程

效果

代码

public partial class Form : Form
{
    public Form()
    {
        InitializeComponent();
    }
    string strg;//数据库路径
    OleDbConnection conn;//数据连接对象
    OleDbCommand cmd;//OleDbCommand对象
    OleDbDataReader sdr;//OleDbDataReader对象

    private bool CheckCard(string cardId)//创建一个CheckCard方法用于检查身份证号码是否合法
    {
        if (cardId.Length ==)        //如果身份证号为18位
        {
           return  CheckCard(cardId);//调用CheckCard18方法验证
        }
        else if (cardId.Length ==)   //如果身份证号为15位
        {
            return CheckCard(cardId);//调用CheckCard15方法验证
        }
        else
        {
            return false;
        }
    }

    private bool CheckCard(string CardId)//CheckCard18方法用于检查18位身份证号码的合法性
    {
        long n =;
        bool flag = false;
        if (long.TryParse(CardId.Remove(), out n) == false || n < Math.Pow(10, 16) || long.TryParse(CardId.Replace('x', '0').Replace('X', '0'), out n) == false)
            return false;//数字验证
        string[] Myaddress =new string[]{ "","22","35","44","53","12",
            "","36","45","54","13","31","37","46","61","14","32","41",
            "","62","15","33","42","51","63","21","34","43","52","64",
            "","71","81","82","91"};
        for (int kk =; kk < Myaddress.Length;kk++ )
        {
            if (Myaddress[kk].ToString() == CardId.Remove())
            {
                flag = true;
            }
        }
        if (flag)
        {
            return flag;
        }
        string Mybirth = CardId.Substring(, 8).Insert(6, "-").Insert(4, "-");
         DateTime Mytime = new DateTime();
        if (DateTime.TryParse(Mybirth, out Mytime) == false)
            return false;//生日验证
        string[] MyVarifyCode = (",0,x,9,8,7,6,5,4,3,2").Split(',');
        string[] wi = (",9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
        char[] ai = CardId.Remove().ToCharArray();
        int sum =;
        for (int i =; i < 17; i++)
            sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
        int y = -;
        Math.DivRem(sum,, out y);
        if (MyVarifyCode[y] != CardId.Substring(, 1).ToLower())
        {
            return false;//校验码验证
        }
        return true;//符合GB-1999标准
    }

    private bool CheckCard(string CardId)
    {
        long n =;
        bool flag = false;
        if (long.TryParse(CardId, out n) == false || n < Math.Pow(, 14))
            return false;//数字验证
        string[] Myaddress = new string[]{ "","22","35","44","53","12",
            "","36","45","54","13","31","37","46","61","14","32","41",
            "","62","15","33","42","51","63","21","34","43","52","64",
            "","71","81","82","91"};
        for (int kk =; kk < Myaddress.Length; kk++)
        {
            if (Myaddress[kk].ToString() == CardId.Remove())
            {
                flag = true;
            }
        }
        if (flag)
        {
            return flag;
        }
        string Mybirth = CardId.Substring(, 6).Insert(4, "-").Insert(2, "-");
        DateTime Mytime = new DateTime();
        if (DateTime.TryParse(Mybirth, out Mytime) == false)
        {
            return false;//生日验证
        }
        return true;//符合位身份证标准
    }

    private void button_Click(object sender, EventArgs e)
    {
        if (txtCardID.Text == "")//如果没有输入身份证号码
        {
            return;              //不执行操作
        }
        else
        {
            if (CheckCard(txtCardID.Text.Trim()))//如果通过CheckCard方法验证成功
            {
                this.Height =;               //设置窗体高度
                string card=txtCardID.Text.Trim();//获取输入的身份证号码
                if (card.Length ==)          //如果输入的是15位的身份证号码,需要将其转换成18位
                {
                    int[] w = new int[] {, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };
                    char[] a = new char[] { '', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2' };
                    string newID = "";
                    int s =;
                    newID =this.txtCardID.Text.Trim().Insert(, "19");
                    for (int i =; i < 17; i++)
                    {
                         int k = Convert.ToInt(newID[i]) * w[i];
                         s = s + k;
                    }
                    int h =;
                    Math.DivRem(s,, out h);
                    newID = newID + a[h];
                    card = newID;               //最后将转换成位的身份证号码赋值给card
                }
                int addnum =Convert.ToInt(card.Remove(6));//获取身份证号码中的地址码
                //连接数据库
                conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB..0;Data source=" + strg);
                conn.Open();//打开数据库
                //查找数据库中是否存在输入的身份证号码中的地址码
                cmd = new OleDbCommand("select count(*) from address where AddNum="+addnum, conn);
                int KK = Convert.ToInt(cmd.ExecuteScalar());
                if (KK >)//如果存在
                {
                    //检索数据库
                    cmd = new OleDbCommand("select * from address where AddNum=" + addnum, conn);
                    //实例化OleDbDataReader对象
                    sdr = cmd.ExecuteReader();
                    sdr.Read();//读取该对象
                    string address = sdr["AddName"].ToString();//获取地址码对应的归属地
                    string birthday = card.Substring(, 8);//从身份证号码中截取出公民的生日
                    string byear = birthday.Substring(,4);//获取出生年份
                    string bmonth = birthday.Substring(,2);//获取出生月份
                    if (bmonth.Substring(, 1) == "0")//如果月份是以0开头
                    {
                        bmonth = bmonth.Substring(,1);//去掉0
                    }
                    string bday = birthday.Substring(,2);//获取出生“日”
                    if (bday.Substring(, 1) == "0")//如果“日”以0开头
                    {
                        bday = bday.Substring(, 1);//去掉0
                    }
                    string sex = "";//性别
                    if (txtCardID.Text.Trim().Length ==)//如果输入的身份证号码是15位
                    {
                        int PP=Convert.ToInt(txtCardID.Text.Trim().Substring(14,1))%2;//判断最后一位是奇数还是偶数
                        if (PP ==)//如果是偶数
                        {
                            sex = "女";//说明身份证号码的持有者是女性
                        }
                        else
                        {
                            sex = "男";//如果是奇数则身份证号码的持有者是男性
                        }
                    }
                    if (txtCardID.Text.Trim().Length ==)//如果输入的身份证号码是18位
                    {
                        int PP = Convert.ToInt(txtCardID.Text.Trim().Substring(16, 1)) % 2;//判断倒数第二位是奇数还是偶数
                        if (PP ==)//如果是偶数
                        {
                            sex = "女";//说明身份证号码的持有者是女性
                        }
                        else
                        {
                            sex = "男";//如果是奇数则身份证号码的持有者是男性
                        }
                    }
                    sdr.Close();//关闭OleDbDataReader连接
                    conn.Close();//关闭数据库连接
                    lblAddress.Text = address;//显示身份证持有者的归属地
                    lblbirthday.Text = byear + "年" + bmonth + "月" + bday + "日";//显示身份证持有者的生日
                    lblsex.Text = sex;//显示身份证持有者的性别
                    lblresult.Text = "合法的公民身份证号!";//显示验证结果
                }
                else
                {
                    MessageBox.Show("公民身份证号输入有误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("非法公民身份证号!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }

    private void button_Click(object sender, EventArgs e)
    {
        txtCardID.Text = "";//清空输入框
        this.Height =;   //设置窗体高度位78
    }

    private void Form_Load(object sender, EventArgs e)
    {
        this.Height =;//设置窗体高度
        //获取数据库路径
        strg = Application.StartupPath.ToString();
        strg = strg.Substring(, strg.LastIndexOf("\\"));
        strg = strg.Substring(, strg.LastIndexOf("\\"));
        strg += @"\db.mdb";
    }
}
partial class Form
{
    /// <summary>
    /// 必需的设计器变量。
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// 清理所有正在使用的资源。
    /// </summary>
    /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows 窗体设计器生成的代码

    /// <summary>
    /// 设计器支持所需的方法 - 不要
    /// 使用代码编辑器修改此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {
        this.label = new System.Windows.Forms.Label();
        this.txtCardID = new System.Windows.Forms.TextBox();
        this.button = new System.Windows.Forms.Button();
        this.button = new System.Windows.Forms.Button();
        this.label = new System.Windows.Forms.Label();
        this.label = new System.Windows.Forms.Label();
        this.label = new System.Windows.Forms.Label();
        this.label = new System.Windows.Forms.Label();
        this.lblAddress = new System.Windows.Forms.Label();
        this.lblbirthday = new System.Windows.Forms.Label();
        this.lblsex = new System.Windows.Forms.Label();
        this.lblresult = new System.Windows.Forms.Label();
        this.SuspendLayout();
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(13, 13);
        this.label.Name = "label1";
        this.label.Size = new System.Drawing.Size(65, 12);
        this.label.TabIndex = 0;
        this.label.Text = "身份证号:";
        // 
        // txtCardID
        // 
        this.txtCardID.Location = new System.Drawing.Point(, 10);
        this.txtCardID.Name = "txtCardID";
        this.txtCardID.Size = new System.Drawing.Size(, 21);
        this.txtCardID.TabIndex =;
        // 
        // button
        // 
        this.button.Location = new System.Drawing.Point(289, 9);
        this.button.Name = "button1";
        this.button.Size = new System.Drawing.Size(75, 23);
        this.button.TabIndex = 2;
        this.button.Text = "开始验证";
        this.button.UseVisualStyleBackColor = true;
        this.button.Click += new System.EventHandler(this.button1_Click);
        // 
        // button
        // 
        this.button.Location = new System.Drawing.Point(367, 8);
        this.button.Name = "button2";
        this.button.Size = new System.Drawing.Size(75, 23);
        this.button.TabIndex = 3;
        this.button.Text = "重新验证";
        this.button.UseVisualStyleBackColor = true;
        this.button.Click += new System.EventHandler(this.button2_Click);
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(13, 53);
        this.label.Name = "label2";
        this.label.Size = new System.Drawing.Size(65, 12);
        this.label.TabIndex = 4;
        this.label.Text = "所属地区:";
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(37, 90);
        this.label.Name = "label3";
        this.label.Size = new System.Drawing.Size(41, 12);
        this.label.TabIndex = 5;
        this.label.Text = "生日:";
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(37, 129);
        this.label.Name = "label4";
        this.label.Size = new System.Drawing.Size(41, 12);
        this.label.TabIndex = 6;
        this.label.Text = "性别:";
        // 
        // label
        // 
        this.label.AutoSize = true;
        this.label.Location = new System.Drawing.Point(13, 169);
        this.label.Name = "label5";
        this.label.Size = new System.Drawing.Size(65, 12);
        this.label.TabIndex = 7;
        this.label.Text = "验证结果:";
        // 
        // lblAddress
        // 
        this.lblAddress.AutoSize = true;
        this.lblAddress.Location = new System.Drawing.Point(, 53);
        this.lblAddress.Name = "lblAddress";
        this.lblAddress.Size = new System.Drawing.Size(, 12);
        this.lblAddress.TabIndex =;
        // 
        // lblbirthday
        // 
        this.lblbirthday.AutoSize = true;
        this.lblbirthday.Location = new System.Drawing.Point(, 90);
        this.lblbirthday.Name = "lblbirthday";
        this.lblbirthday.Size = new System.Drawing.Size(, 12);
        this.lblbirthday.TabIndex =;
        // 
        // lblsex
        // 
        this.lblsex.AutoSize = true;
        this.lblsex.Location = new System.Drawing.Point(, 129);
        this.lblsex.Name = "lblsex";
        this.lblsex.Size = new System.Drawing.Size(, 12);
        this.lblsex.TabIndex =;
        // 
        // lblresult
        // 
        this.lblresult.AutoSize = true;
        this.lblresult.Location = new System.Drawing.Point(, 169);
        this.lblresult.Name = "lblresult";
        this.lblresult.Size = new System.Drawing.Size(, 12);
        this.lblresult.TabIndex =;
        // 
        // Form
        // 
        this.AutoScaleDimensions = new System.Drawing.SizeF(F, 12F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(, 192);
        this.Controls.Add(this.lblresult);
        this.Controls.Add(this.lblsex);
        this.Controls.Add(this.lblbirthday);
        this.Controls.Add(this.lblAddress);
        this.Controls.Add(this.label);
        this.Controls.Add(this.label);
        this.Controls.Add(this.label);
        this.Controls.Add(this.label);
        this.Controls.Add(this.button);
        this.Controls.Add(this.button);
        this.Controls.Add(this.txtCardID);
        this.Controls.Add(this.label);
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
        this.MaximizeBox = false;
        this.MinimizeBox = false;
        this.Name = "Form";
        this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
        this.Text = "验证身份证号码";
        this.Load += new System.EventHandler(this.Form_Load);
        this.ResumeLayout(false);
        this.PerformLayout();

    }

    #endregion

    private System.Windows.Forms.Label label;
    private System.Windows.Forms.TextBox txtCardID;
    private System.Windows.Forms.Button button;
    private System.Windows.Forms.Button button;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Label label;
    private System.Windows.Forms.Label lblAddress;
    private System.Windows.Forms.Label lblbirthday;
    private System.Windows.Forms.Label lblsex;
    private System.Windows.Forms.Label lblresult;

}