c# 实现手机号验证(非正则)

时间:2022-11-06 19:30:49

手机号验证一般都会使用正则表达式来做,但是今天遇到一个手机号,166***4926,正则里是不允许166开头的手机,于是用户的注册出了问题。这里介绍一种不是那么适用的方法来校验。这个方法最好在正则未通过之后进行调用,检测该手机号是否为手机号。话不多说,上代码。

public class Mobile
    {public string Mobile_Number;
        public string province;
        public string city;
        public string Service_provider;
        public static Mobile CheckMoblie(string mobile)
        {
            try
            {
                
                string url = "https://www.baidu.com/s?ie=UTF-8&wd="+mobile;
                var res = Get(url);
                if (res.Contains("<em>" + mobile + "</em>"))
                {
                    var relationstr = "<div class=\"op_mobilephone_r c-gap-bottom-small\">";
                    var p = res.IndexOf(relationstr);
                    res = res.Substring(p);

                    var p1 = res.IndexOf("</div>");
                    res = res.Substring(0, p1);

                    var array = res.Split(new string[] { "<span>", "</span>" }, StringSplitOptions.RemoveEmptyEntries);

                    var temp = 1;

                    List<string> UserfulMsgInfo = new List<string>();
                    UserfulMsgInfo.Add(array[1]);
                    UserfulMsgInfo.Add(array[3]);

                    var temp1 = UserfulMsgInfo[0].Split(new string[] { "&quot;" }, StringSplitOptions.RemoveEmptyEntries);
                    var temp2 = UserfulMsgInfo[1].Split(new string[] { "&nbsp;" }, StringSplitOptions.RemoveEmptyEntries);


                    Mobile M = new Mobile();
                    M.IsMobile = true;
                    M.Mobile_Number = temp1[1];
                    M.province = temp2[0];
                    M.Service_provider = temp2[2];
                    M.city = temp2[1];

                    return M;
                }


                return null;
            }
            catch
            {
                return null;
            }
        }

        private static String Get(string url)
        {
            System.Net.HttpWebRequest request = System.Net.WebRequest.Create(url) as System.Net.HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36";//非常重要
            //request.UserAgent = DefaultUserAgent;
            System.Net.HttpWebResponse result = request.GetResponse() as System.Net.HttpWebResponse;
            System.IO.StreamReader sr = new System.IO.StreamReader(result.GetResponseStream(), Encoding.UTF8);
            string strResult = sr.ReadToEnd();
            sr.Close();
            
            return strResult;
        }
    }

在你的正则不通过的时候调用CheckMoblie方法,自动返回一个手机号的对象,如果是null则为非手机号,如果有则会返回一个Mobile对象。

 

但是该代码非常不稳定,后续再慢慢优化。

 

轻喷,谢谢。