Adam Higgins
Adam Higgins

Reputation: 754

Telephone number validation

I have this code to validate a phone number but it looks a bit awkward. I'm guessing theres a better way to go about this. 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;
}

Upvotes: 5

Views: 8262

Answers (3)

Richard
Richard

Reputation: 30628

Don't try and do this yourself, use a library where someone has already done the hard work for you, such as 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. Not only will this ensure that the number is valid in the relevant country, it will also allow you to filter out premium numbers and "fake" numbers (such as 555 in the US).

Upvotes: 7

fubo
fubo

Reputation: 46005

try

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

Where the regex checks whether there is only a single number (1 to 7 digits) with + in front of them read. The drawback, this way you cannot further processed, you might need to read the line from console to a new variable.

Upvotes: 3

Andrey Korneyev
Andrey Korneyev

Reputation: 26886

Your goal can be easily achieved using regular expressions:

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

This pattern is exactly as stated: consists of integers, is less than 8 digits in length and has a plus at the start, and also this pattern can be modified if conditions somehow more complex.

Upvotes: 5

Related Questions