电话号码验证

Ada*_*ins 3 c#

我有这个代码来验证电话号码,但它看起来有点尴尬.我猜这是一个更好的方法来解决这个问题.我怎样才能提高效率呢?

public static bool validTelephoneNo(string telNo)
{
    bool condition = false;
    while (condition == false)
    {
        Console.WriteLine("Enter a phone number.");
        telNo = Console.ReadLine();
        if (telNo.Length > 8)
        {
            if (telNo.StartsWith("+") == true)
            {
                char[] arr = telNo.ToCharArray();
                for (int a = 1; a < telNo.Length; a++)
                {
                    int temp;

                    try
                    {
                        temp = arr[a];
                    }

                    catch
                    {
                        break;
                    }

                    if (a == telNo.Length - 1)
                    {
                        condition = true;
                    }
                }
            }
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

And*_*yev 5

使用正则表达式可以轻松实现您的目标:

public static bool validTelephoneNo(string telNo)
{
    return Regex.Match(telNo, @"^\+\d{1,7}$").Success;
}
Run Code Online (Sandbox Code Playgroud)

这种模式完全符合规定:由整数组成,长度小于 8 位,开头有一个加号,如果条件更复杂,也可以修改这种模式。


Ric*_*ard 5

不要自己尝试这样做,使用一个已经为你做过艰苦工作的图书馆,比如libphonenumber.

例:

public static bool validTelephoneNo(string telNo)
{
    PhoneNumber number;
    try
    {
        number = PhoneNumberUtil.Instance.Parse(telNo, "US");  // Change to your default language, international numbers will still be recognised.
    }
    catch (NumberParseException e)
    {
        return false;
    }

    return number.IsValidNumber;
}
Run Code Online (Sandbox Code Playgroud)

该库将处理来自不同国家/地区的电话号码的解析和格式化.这不仅可以确保该号码在相关国家/地区有效,还可以过滤掉保费号码和"假"号码(例如美国的555号码).