Phone number verification

I have this code to check a phone number, but it looks a little awkward. I guess this is the best way to do it. How can I make this more efficient?

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;
}

      

+3


source to share


3 answers


Your goal can be easily achieved with regular expressions:

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

      



This pattern is exactly the same as indicated: consists of integers, is less than 8 digits long and has a plus at the beginning, and this pattern can be modified if the conditions are somehow more complex.

+3


source


Don't try to do it yourself, use a library where someone else has already done the hard work for you, like libphonenumber .

Example:



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;
}

      

This library will handle parsing and formatting phone numbers from different countries. This not only ensures that the number is valid in the respective country, it will also allow you to filter out premium numbers and “fake” numbers (eg 555 in the US).

+5


source


try

Console.WriteLine("Enter a phone number.");
bool isValid = new System.Text.RegularExpressions.Regex(@"^[+]\d{1,7}$").IsMatch(Console.ReadLine());

      

If the regex is checking if there is only one number (1 to 7 digits) with +

before them, read it. The downside is that you cannot process anymore, you may need to read the line from the console to a new variable.

+3


source







All Articles