Adam Higgins Adam Higgins - 3 months ago 23
C# Question

How to validate a phone number

A valid phone number contains:

less than 9 characters,
a "+" at the start,
and only digits.

Im trying to use regular expressions but i've only started using them and im not good at it. The code i have so far is:

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


But i don't know how to check the length of the string this way. Any help is appreciated.

Answer

Jacek's regex works fine

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