C#中身份证验证的功能模块(18位)

一段简单的身份证校验代码,由身份证的前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输入
            }
        }
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值