iT邦幫忙

DAY 17
4

看範例學C#系列 第 17

看範例學C#-17 驗證身份證字號

驗證身份證字號範例
驗證身份證字號是個蠻常用的功能,像員工資料還是會員資料都蠻常會需要
需入身份證字號,為了要避免輸入錯誤,及故意打錯,所以我們要做好防呆
正確的時候才存起來,不正確就要提示錯誤
通常儲存前也要先檢查一次是否存在,避免資料重覆建立
以下為本範例程式碼及註解

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 ex17
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            textBox1.MaxLength = 10;//設定字元數最大值
            textBox1.Focus();//程式啟動就把焦點移到textBox1
            this.AcceptButton = button1;//按下enter就觸發button click事件
        }

        private void button1_Click(object sender, EventArgs e)
        {
           if (textBox1.Text.Trim().Length==10)//長度達十個字才驗證
           {
               if (isIdentificationId(textBox1.Text))//驗證身份證字號,正確回傳true
               {
                   textBox1.Text = textBox1.Text.ToUpper();//英文自動轉成大寫
                   MessageBox.Show(textBox1.Text + "是正確的身份證字號", "", MessageBoxButtons.OK, MessageBoxIcon.None);
               }
               else//驗證身份證字號,不正確回傳false
               {
                   MessageBox.Show("身份證字號有誤", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
               }
           }
           else
           {
               MessageBox.Show("身份證字號有誤", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
           }
        }
        #region checkID
        public static bool isIdentificationId(string arg_Identify)
        {
            var d = false;
            if (arg_Identify.Length == 10)
            {
                arg_Identify = arg_Identify.ToUpper();
                if (arg_Identify[0] >= 0x41 && arg_Identify[0] <= 0x5A)
                {
                    var a = new[] { 10, 11, 12, 13, 14, 15, 16, 17, 34, 18, 19, 20, 21, 22, 35, 23, 24, 25, 26, 27, 28, 29, 32, 30, 31, 33 };
                    var b = new int[11];
                    b[1] = a[(arg_Identify[0]) - 65] % 10;
                    var c = b[0] = a[(arg_Identify[0]) - 65] / 10;
                    for (var i = 1; i <= 9; i++)
                    {
                        b[i + 1] = arg_Identify[i] - 48;
                        c += b[i] * (10 - i);
                    }
                    if (((c % 10) + b[10]) % 10 == 0)
                    {
                        d = true;
                    }
                }
            }
            return d;
        }
        #endregion
    }
}


全系列文章列表


上一篇
看範例學C#-16 使用Windows Media Player播放影片
下一篇
看範例學C#-18 Regular Expression 規則運算式
系列文
看範例學C#30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 則留言

0
120131511
iT邦研究生 4 級 ‧ 2011-10-15 11:04:31

沒想到c#可以使用 var 這種像JavaScript資料型態,一直沒注意到,感謝分享。

0

我要留言

立即登入留言