天天看點

Winform 驗證輸入TextBox身份證号是否有效

private void btnView_Click(object sender, EventArgs e)
        {
            string id = txtID.Text.Trim();
            int age = 0;
            int year = 0;
            if (id.Length == 15)
            {
                year = Convert.ToInt32(id.Substring(6, 2)) + 1900;      //截取字元串id第6位第7位
                
            }
            else if (id.Length == 18)
            {
                if(!this.CheckCardId(id))             //若CheckCardId傳回值為false,提醒并return
                {
                    MessageBox.Show("身份證号有誤,請檢查!");
                    return;
                }
                year = Convert.ToInt32(id.Substring(6, 4));        //截取字元串id第6位第7位
                
            }
            else
            {
                MessageBox.Show("你輸入的身份證号長度有誤!");
                return;
            }

            age = DateTime.Now.Year - year;                 //計算使用者的年齡    

                if (age >= 18)
                {
                    picGirls.Visible = true;
                }
                else
                {
                    MessageBox.Show("你太小了,圖檔不宜檢視!");
                }

        }

        /// <summary>
        /// 校驗身份證号,若正确則傳回true,否則傳回false
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private bool CheckCardId(string id)
        {
            string number17 = id.Substring(0, 17);
            string number18 = id.Substring(17);
            int[] wQuan = { 7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};            //權重因子數組
            string checkWei = "10X98765432";                              //校驗碼數組
            int sum = 0;
            for (int i = 0; i < 17; i++)
            {
                sum = sum + Convert.ToInt32(number17[i].ToString()) * wQuan[i];
            }
            int mod = sum % 11;                                     //除以11取模
            string result = checkWei[mod].ToString();      
            if(number18.Equals(result,StringComparison.OrdinalIgnoreCase))    //字元串比較,忽略大小寫
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        private void txtID_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                e.Handled = true;
            }
            //如果身份證的第18位輸入的是x或X,則不阻止
            if ((txtID.SelectionStart == 17) && (e.KeyChar == 'x' || e.KeyChar == 'X'))
            {
                e.Handled = false;
            }
            //空格鍵不阻止
            if (e.KeyChar == 8)
            {
                e.Handled = false;
            }
        }

        private void txtID_TextChanged(object sender, EventArgs e)
        {
            picGirls.Visible = false;
        }