Priscila
Priscila

Reputation: 301

Validate phone numbers in c# (Console)

Can I restrict the phone numbers in my console app without regular expressions? I have this code, but it doesn´t work with international numbers, begining with 00.

   static public bool CheckPhoneNumb (string phoneNumber)
    {
        long lphoneNumber;
        return ((phoneNumber.Length >= 9) && phoneNumber.Length <= 15) &&
                (long.TryParse (phoneNumber, out lphoneNumber))) ? true : false;
    }

Thnks.

Upvotes: 0

Views: 3565

Answers (4)

Nicholas Carey
Nicholas Carey

Reputation: 74355

The answer you seek is rather more complex than you might think.

Often the number itself varies depending one the origin and destination locale as prefixes get added/removed.

What kind of phone numbers? NANP (North American Numbering Plan) or somewhere else?

The NANP, which covers the US, Canada, Mexico and the Carribean is described at http://www.nanpa.com/. For numbering plans in place around the world, a good place to start is at the World Telephone Numbering Guide at http://www.wtng.info/

Upvotes: 1

Robert McKee
Robert McKee

Reputation: 21477

International phone numbers don't begin with 00. The 00 part is the code that you use in your part of the world to begin dialing the actual international number (which follows the 00). That number changes from where you are dialing from. For example, in the US, it is 011. In Europe, it is 00. Japan has a different code, and there are a few others.

Yes, you can restrict it without regular expressions, but you would probably find it easier to, and I would highly recommend you don't store your (or any) international access code with it, as it varies according to whom you display it to.

Upvotes: 1

Ahmed KRAIEM
Ahmed KRAIEM

Reputation: 10427

return ((phoneNumber.Length >= 9) && phoneNumber.Length <= 15) && phoneNumber.All(char.IsNumber);

Upvotes: -1

Eric J.
Eric J.

Reputation: 150198

If you need to support worldwide calling, you will have a hard time doing so with regular expressions.

I would suggest the Google Phone Number Validation Library.

Parsing/formatting/validating phone numbers for all countries/regions of the world.

https://code.google.com/p/libphonenumber/

There's a C# port linked at the bottom of the page.

Upvotes: 5

Related Questions