【问题标题】:How to validate a (country specific) phone number如何验证(特定国家/地区)电话号码
【发布时间】:2015-04-30 14:19:21
【问题描述】:

一个有效的电话号码包含:

  • 少于 9 个字符
  • “+”开头
  • 只有数字。

我正在尝试使用正则表达式,但我才开始使用它们而且我并不擅长。我到目前为止的代码是:

static void Main(string[] args)
{
    Console.WriteLine("Enter a phone number.");
    string telNo = Console.ReadLine();

    if (Regex.Match(telNo, @"^(\+[0-9])$").Success)
        Console.WriteLine("correctly entered");

    else
        Console.WriteLine("incorrectly entered");

    Console.ReadLine();
}

但我不知道如何以这种方式检查字符串的长度。任何帮助表示赞赏。

【问题讨论】:

  • 您想在服务器代码 (c#) 或 java 脚本中使用您的正则表达式?我不确定,但可能会有一些差异
  • 有效的电话号码是否包含少于 9 个字符,这不取决于您所在的国家/地区吗?
  • 嘎。这个问题太可怕了;它提供了“有效电话号码”的定义,这并不是有效电话号码的真正定义(我不知道一个国家的电话号码包括国家代码少于 9 个字符,实际上- 至少对于美国或英国来说不是这样),但目前的标题没有暗示这一点,答案从表面上看是奇怪的定义。旨在反 SEO 这个问题并阻止 Google 员工登陆这里的标题编辑似乎是为了......
  • 警告:整个线程假定美国北美电话号码。使用支持国际号码的库。 nuget.org/packages/libphonenumber-csharp

标签: c# regex


【解决方案1】:

Jacek 的正则表达式运行良好

public class Program
{
    public static void Main()
    {
        Console.WriteLine("Enter a phone number.");
        string telNo = Console.ReadLine();                      
        Console.WriteLine("{0}correctly entered", IsPhoneNumber(telNo) ? "" : "in");    
        Console.ReadLine(); 
    }

    public static bool IsPhoneNumber(string number)
    {
        return Regex.Match(number, @"^(\+[0-9]{9})$").Success;
    }
}

【讨论】:

    【解决方案2】:

    您的正则表达式应如下所示,您需要有关字符计数器的信息

    @"^(\+[0-9]{9})$"
    

    【讨论】:

    • 该站点的 C# 正则表达式设置是什么?我只看到 PHP、Javascript 和 Python。
    • @Jacek 电话代码呢? (+1、+880、+965 等)
    • @FaizanRabbani 你想输入以加号开头的内容吗?
    • @jacek 是的。我用@"^\+[0-9]{0,3}$"算出来的,你怎么看?
    【解决方案3】:

    不要使用正则表达式!!

    正则表达式的变量太多而无法使用。相反,只需从字符串中删除所有不是 0-9 的字符,然后检查剩余的位数是否正确。那么用户包含或不包含什么额外的东西并不重要...... ()x-+[] 等等,因为它只是将它们全部剥离并且只计算字符 0-9。

    我有一个很好用的字符串扩展,它支持多种格式。它接受IsRequired 参数。因此,您可以像这样验证电话号码:

    string phone = "(999)999-9999"
    bool isValidPhone = phone.ValidatePhoneNumber(true) // returns true
    
    string phone ="1234567890"
    bool isValidPhone = phone.ValidatePhoneNumber(true) // returns true
    
    string phone = ""
    bool isValidPhone = phone.ValidatePhoneNumber(false) // not required, so returns true
    
    string phone = ""
    bool isValidPhone = phone.ValidatePhoneNumber(true) // required, so returns false
    
    string phone ="12345"
    bool isValidPhone = phone.ValidatePhoneNumber(true) // returns false
    
    string phone ="foobar"
    bool isValidPhone = phone.ValidatePhoneNumber(true) // returns false
    

    这是代码(假设是 10 位数的美国电话号码。相应调整):

    public static class StringExtensions
    {
    
        /// <summary>
        /// Checks to be sure a phone number contains 10 digits as per American phone numbers.  
        /// If 'IsRequired' is true, then an empty string will return False. 
        /// If 'IsRequired' is false, then an empty string will return True.
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="IsRequired"></param>
        /// <returns></returns>
        public static bool ValidatePhoneNumber(this string phone, bool IsRequired)
        {
            if (string.IsNullOrEmpty(phone) & !IsRequired)
                return true;
    
            if (string.IsNullOrEmpty(phone) & IsRequired)
                return false;
    
            var cleaned = phone.RemoveNonNumeric();
            if (IsRequired)
            {
                if (cleaned.Length == 10)
                    return true;
                else
                    return false;
            }
            else
            {
                if (cleaned.Length == 0)
                    return true;
                else if (cleaned.Length > 0 & cleaned.Length < 10)
                    return false;
                else if (cleaned.Length == 10)
                    return true;
                else
                    return false; // should never get here
            }
        }
    
        /// <summary>
        /// Removes all non numeric characters from a string
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public static string RemoveNonNumeric(this string phone)
        {
            return Regex.Replace(phone, @"[^0-9]+", "");
        }
    }
    

    【讨论】:

    • 你是我的英雄。我喜欢你处理这件事的方式。
    • 希望对您有所帮助:)
    • 注意:此方法仅适用于美国电话号码。在我的国家(波兰),我们有 9 位数的手机号码。此外,人们有时会添加国家/地区代码(波兰为 +48),因为没有它,号码在其他欧盟国家/地区将无法使用(好吧,如果有人在其他国家/地区拥有此号码,则可能:D)。
    • @Makalele,是的,你是对的。我在答案中提到,这仅适用于 10 位数的美国电话号码,您需要对其他任何内容进行相应修改!
    【解决方案4】:

    扩展上面提供的答案之一,我想出的同时处理一些电话号码传递方式以及国际电话号码的方法是

        internal static bool IsValidPhoneNumber(this string This)
        {
            var phoneNumber = This.Trim()
                .Replace(" ", "")
                .Replace("-", "")
                .Replace("(", "")
                .Replace(")", "");
            return Regex.Match(phoneNumber, @"^\+\d{5,15}$").Success;
        }
    

    【讨论】:

      【解决方案5】:

      这样的事情可能会奏效:

      ^+\d{0,9}

      但我建议使用正则表达式测试器来了解更多关于正则表达式如何工作的信息。我自己还是喜欢大量使用它们,因为我不经常写正则表达式。这是一个示例,但还有更多示例。

      https://regex101.com/

      【讨论】:

        【解决方案6】:

        Valid USAPhoneNumber 的简单函数。

           /// <summary>
            /// Allows phone number of the format: NPA = [2-9][0-8][0-9] Nxx = [2-9]      [0-9][0-9] Station = [0-9][0-9][0-9][0-9]
            /// </summary>
            /// <param name="strPhone"></param>
            /// <returns></returns>
            public static bool IsValidUSPhoneNumber(string strPhone)
            {
                string regExPattern = @"^[01]?[- .]?(\([2-9]\d{2}\)|[2-9]\d{2})[- .]?\d{3}[- .]?\d{4}$";
                return MatchStringFromRegex(strPhone, regExPattern);
            }
            // Function which is used in IsValidUSPhoneNumber function
            public static bool MatchStringFromRegex(string str, string regexstr)
            {
                str = str.Trim();
                System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(regexstr);
                return pattern.IsMatch(str);
            }
        

        【讨论】:

          【解决方案7】:

          如果您正在寻找特定国家/地区的正则表达式,请尝试适用于所有澳大利亚 (+61-) 数字的表达式。我已经向 cmets 介绍了如何将其更改为其他用途。

          public static bool IsValidPhoneNumber(string phoneNumber)
          {
              //will match +61 or +61- or 0 or nothing followed by a nine digit number
              return Regex.Match(phoneNumber, 
                  @"^([\+]?61[-]?|[0])?[1-9][0-9]{8}$").Success;
              //to vary this, replace 61 with an international code of your choice 
              //or remove [\+]?61[-]? if international code isn't needed
              //{8} is the number of digits in the actual phone number less one
          }
          

          【讨论】:

            【解决方案8】:

            此解决方案可验证用于验证电话号码的每个测试标准,它还利用 Regex API。标准包括间距、任何非数值、区号(您指定)、电话号码应具有的值(位数),还包括错误消息以及电话号码的新旧状态。

            这里是源代码:

            public class PhoneNumberValidator
            {
                public string ErrorMessage { get; set; }
                public int PhoneNumberDigits { get; set; }
                public string CachedPhoneNumber { get; set; }
            
                private Dictionary<int, string> VaildAreaCodes()
                {
                    return new Dictionary<int, string>
                    {
                        [3] = "0",
                        [4] = "27"
                    };
                }
            
                private bool IsInteger(string value)
                {
                    return int.TryParse(value, out int result);
                }
            
                private string GetConsecutiveCharsInPhoneNumberStr(string phoneNumber)
                {
                    switch (PhoneNumberDigits)
                    {
                        case 0:
                        case 10:
                            PhoneNumberDigits = 10;
                            return phoneNumber.Substring(phoneNumber.Length - 7);
            
                        case 11:
                            return phoneNumber.Substring(phoneNumber.Length - 8);
            
                        default:
                            return string.Empty;
                    }
                }
            
                private bool IsValidAreaCode(ref string phoneNumber, string areaCode)
                {
                    if (!IsInteger(areaCode))
                    {
                        ErrorMessage = "Area code characters of Phone Number value should only contain integers.";
                        return false;
                    }
            
                    var areaCodeLength = areaCode.Length;
                    var invalidAreaCodeMessage = "Phone Number value contains invalid area code.";
                    switch (areaCodeLength)
                    {
                        case 2:
                            phoneNumber = string.Concat("0", phoneNumber);
                            return true;
            
                        case 3:
                            if (!areaCode.StartsWith(VaildAreaCodes[3]))
                                ErrorMessage = invalidAreaCodeMessage;
                            return string.IsNullOrWhiteSpace(ErrorMessage) ? true : false;
            
                        case 4:
                            if (areaCode.StartsWith(VaildAreaCodes[4]))
                            {
                                phoneNumber = string.Concat("0", phoneNumber.Remove(0, 2)); // replace first two charaters with zero
                                return true;
                            }                    
                            ErrorMessage = invalidAreaCodeMessage;
                            return false;                
            
                        default:
                            ErrorMessage = invalidAreaCodeMessage;
                            return false;
                    }
                }   
            
                public bool IsValidPhoneNumber(ref string phoneNumber)
                {
                    CachedPhoneNumber = phoneNumber;
            
                    if (string.IsNullOrWhiteSpace(phoneNumber))
                    {
                        ErrorMessage = "Phone Number value should not be equivalent to null.";
                        return false;
                    }
            
                    phoneNumber = Regex.Replace(phoneNumber, " {2,}", string.Empty); // remove all whitespaces
                    phoneNumber = Regex.Replace(phoneNumber, "[^0-9]", string.Empty); // remove all non numeric characters
            
                    var lastConsecutiveCharsInPhoneNumberStr = GetConsecutiveCharsInPhoneNumberStr(phoneNumber);
            
                    if (string.IsNullOrWhiteSpace(lastConsecutiveCharsInPhoneNumberStr))
                    {
                        ErrorMessage = "Phone Number value not supported.";
                        return false;
                    }
            
                    if (!IsInteger(lastConsecutiveCharsInPhoneNumberStr))
                    {
                        ErrorMessage = "Last consecutive characters of Phone Number value should only contain integers.";
                        return false;
                    }
            
                    var phoneNumberAreaCode = phoneNumber.Replace(lastConsecutiveCharsInPhoneNumberStr, "");
            
                    if (!IsValidAreaCode(ref phoneNumber, phoneNumberAreaCode))
                    {
                        return false;
                    }            
            
                    if (phoneNumber.Length != PhoneNumberDigits)
                    {
                        ErrorMessage = string.Format("Phone Number value should contain {0} characters instead of {1} characters.", PhoneNumberDigits, phoneNumber.Length);
                        return false;
                    }
            
                    return true;
                }
            }
            

            该解决方案具有高度可配置性,可用于任何数字电话号码以及区号。

            【讨论】:

              猜你喜欢
              • 2021-03-24
              • 2021-10-03
              • 2017-03-30
              • 2019-06-14
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-05-22
              相关资源
              最近更新 更多