首页 > 编程 > C# > 正文

C#中判断身份证号是否正确的方法

2023-05-16 12:36:02
字体:
来源:转载
供稿:网友

最近,在一个项目中想判断输入的身份证号是否正确,则自己编写了一个用于判断身份证号是否正确的方法,用于判断用户输入的身份证号是否合法。因为当时项目比较急,写的方法也比较潦草,也没有进行优化,在使用过程中还未发现有错误。

这个方法能够判断15位的身份证号和18位的身份证号。

        /// <summary>
        /// 判断字符串是否为身份证号
        /// </summary>
        /// <param name="strCardCode">输入的字符串</param>
        /// <returns>bool:是否为身份证号</returns>
        public static bool IsCardCode(string strCardCode)
        {
            bool isRight = true;
            if (strCardCode.Length != 18 && strCardCode.Length != 15)
                return false;
            else if (strCardCode.Length == 15)
            {
                try
                {
                    Convert.ToInt64(strCardCode);
                }
                catch
                {
                    return false;
                }

            }
            else if (strCardCode.Length == 18)
            {
                string[] prov ={"11","12","13","14","15","21","22","23","31","32","33","34","35","36","37","41","42","43","44","45","46","50",
                    "51","52","53","54","61","62","63","64","65","81","82"};
                string s1 = strCardCode.Substring(0, 2);
                string s2 = strCardCode.Substring(0, 17);
                string s3 = strCardCode.Substring(6, 8);
                string s4 = s2.Substring(16, 1);
                try
                {
                    Convert.ToInt64(s2);
                }
                catch
                {
                    return false;
                }
                int iPos = 0;
                for (iPos = 0; iPos < prov.Length; iPos++)
                {
                    if (prov[iPos] == s1)
                        break;
                }
                if (iPos >= prov.Length)
                {
                    return false;
                }
                if (Convert.ToInt32(s3.Substring(0, 4)) < 1910 || Convert.ToInt32(s3.Substring(0, 4)) > (DateTime.Now.Year - 10))
                {
                    return false;
                }
                if (Convert.ToInt32(s3.Substring(4, 4).Substring(0, 2)) == 0 || Convert.ToInt32(s3.Substring(4, 4).Substring(0, 2)) > 12)
                {
                    return false;
                }
                int iTmp = Convert.ToInt32(s3.Substring(4, 4).Substring(2, 2));
                if (iTmp == 0 || iTmp > 31)
                {
                    return false;
                }
                if (strCardCode.Substring(17, 1).ToUpper() != "X")
                {
                    try
                    {
                        Convert.ToInt32(strCardCode.Substring(17, 1));
                    }
                    catch
                    {
                        return false;
                    }
                }
            }
            return isRight;
        }

注意:由于项目的特殊性,这个方法将1910年之前出生的以及小于10岁的身份证号视为非法号码,你可以根据需要进行修改。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表