Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate a (country specific) phone number

Tags:

A valid phone number contains:

  • Less than 9 characters
  • A "+" at the start
  • Only digits.

I'm trying to use regular expressions but I've only started using them and I'm 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.

like image 222
Adam Higgins Avatar asked Apr 30 '15 14:04

Adam Higgins


1 Answers

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;     } } 
like image 127
Greg Avatar answered Dec 27 '22 23:12

Greg