ASP.NET身份證識別判定

Simple_Demo發表於2015-04-18

實現身份證的判定 前17位都是數字最後一位X或者x 18位都是數字 查出出生年月性別

if (txtId.Text.Length!= 18)

        {
             //18位身份證號碼

            Response.Write("<script>alert('請輸入18位身份證號碼!')</script>");

           return;

        }
        else {
            // 18位全是數字
       
    System.Text.ASCIIEncoding asci = new System.Text.ASCIIEncoding();
            byte[] bystr = asci.GetBytes(txtId.Text);

          //  第18位是否為x或者X

            if (bystr[17]==88 || bystr[17]==120)

            {   

              //前17位都是數字

                for (int i = 0; i < bystr.Length - 1; i++)
                {
                    if (bystr[i] < 48 || bystr[i] > 57)
                    {

                                Response.Write("<script>alert('前17位都是數字')</script>");

                                      return;

                    }
                    else
                    {
                        //第7-10位是出身的年
                        // 倒數第二位號碼奇數為男偶數為女
                        string sex;
                        string year = txtId.Text.Substring(6, 4);
                        if (bystr[16] % 2 == 0)
                        {
                            sex = "男";
                        }
                        else
                        {
                            sex = "女";
                        }
                       //用一個label控制元件接收
                        lblBoth.Text = "您是" + year + "出生的" + "性別為:" + sex;
                    }
                }
             
            }

            else {

                   //如果18位都是數字

                for (int i = 0; i < bystr.Length; i++)
                {
                    if (bystr[i] < 48 || bystr[i] > 57)
                    {      

                                  Response.Write("<script>alert('18位都是數字!')</script>");

                                      return;

                    }

                    else
                    {
                        //第7-10位是出身的年
                        // 倒數第二位號碼奇數為男偶數為女
                        string sex;
                        string year = txtId.Text.Substring(6, 4);
                        if (bystr[16] % 2 == 0)
                        {
                            sex = "男";
                        }
                        else
                        {
                            sex = "女";
                        }

                        lblBoth.Text = "您是" + year + "出生的" + "性別為:" + sex;
                    }
                }
            }


          


        }

相關文章