Validate phone numbers in c# (Console) - c#

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.

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.

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.

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/

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

Related

Calculate SMS Length/Parts C#

I have been asked to help a friend in his application which has an indicator/counter that should show the end-user how many characters have been written in the text box and also how many parts in this written text/SMS?.
The easiest part was about getting the current characters count/length by using TextBox1.Text.Length, but the other part which was resposible for getting how many parts in this SMS text depending on both Arabic/Unicode and English/7Bit languages, and each language has a different specifications at GSM's side, as the one single Arabic message is 70 characters maximum and 67 for concatenated parts, and for English, it is 160 for the one single part and 153 for the concatenated parts.
We had two options, the first one was that we were getting the SMS from the mobile operator with an encoding parameter which helped us to determine the language of the message if it was 7Bit or Unicode message, so it was easy to check the given encoding parameter value and go ahead with 160 or 70 check, and the other option was to have our own language checker. Anyways, we used the below code and it works perfectly:
public int CalculateSmsLength(string text)
{
if (IsEnglishText(text))
{
return text.Length <= 160 ? 1 : Convert.ToInt32(Math.Ceiling(Convert.ToDouble(text.Length) / 153));
}
return text.Length <= 70 ? 1 : Convert.ToInt32(Math.Ceiling(Convert.ToDouble(text.Length) / 67));
}
public bool IsEnglishText(string text)
{
return Regex.IsMatch(text, #"^[\u0000-\u007F]+$");
}
Math.Ceiling returns the smallest integer greater than or equal to the specified number.
P.S. We had an application was detecting the given text if it was in 7Bit or Unicode encoding, but it is a long code and will post it later under an appropriate title.

Abbreviations used in formatting numbers and localization

I came across this post, Format Number like Stack Overflow (rounded to thousands with K suffix), that explains how to take a number and apply a suffix to the end so that large numbers are shortened and takes up less space while retaining the meaning. SO uses the same basic logic in various places.
I'd like to use similar logic but I noticed that this solution is partially English specific. The suffixes are a mix of English letters (m = million, b = billion) and a metric symbol (k) and I'm wondering how this could be re-written so that it is localizable for other languages.
For example in the post it formats numbers like this:
1.1k = 1,100 thousand. this uses the k metric kilo symbol to denote thousands.
1.4m = 1,400,000 million. this uses the letter m from the English word million to denote millions.
1.6b = 1,600,000,000 billion. this uses the letter b from the English word billion to denote billions.
My questions are:
1) Are metric symbols like k, M, and G recognizable by all cultures? (wikipedia suggests it is for everyone except the US but I have my doubts)
2) Is there something in the .Net BCL that I can use to grab the appropriate single or multi-letter combination for any given language to denote millions and billions like this is currently doing in English?
I thought about just using all metric symbols but G doesn't register as billions for me because I'm from the US ;)
1.1k
1.4M
1.6G
If metric symbols are universally recognized outside of the US then perhaps the above is appropriate for everyone and the US is the only special snowflake which makes this a simple if/else statement.
Fingers crossed that people who speak and write in non-English languages can chime on this.
Introduce culture-specific and/or general units. In simplest case it is just a factor, to example:
ft =m * 3.2808
Have your data in database in default units and simply calculate value depending on the culture and add units to the end of it.
Regarding k, in Russian it become К, so you have to localize units.
In some games there are non-stards units, to example, 1kkk, but it looks like peoples are very easily get used to those (because they are logical), so another approach would be to teach user to your units. In such case it should clear or well documented what unit means what.
One more example, in electronics, 1K5 would means 1.5 KOhm

Formatting International Phone Numbers

I have a project where I have an input for a phone number. Said phone number can be from any country. The user selected the country before entereing the phone number.
Is there a way to format the phone number as a user is typing it in WPF?
I was playing around with Google's library port for C# but to no avail (click here)
Thanks!
I can advise you to use two properties where in a property HomeNumber regular expression is used for formatting number input.
Example (closer to pseudocode):
public string Country
{
get { return country; }
set { country = value; }
}
public string HomeNumber
{
get
{
if (homeNumber == null)
{
return string.Empty;
}
if (country.Equals("USA"))
{
return Regex.Replace(homeNumber, #"(\d{2})(\d{2})(\d{2})", "$1-$2-$3");
}
else if (country.Equals("Russia"))
{
return Regex.Replace(homeNumber, #"(\d{3})(\d{2})(\d{2})", "$1-$2-$3");
}
}
set
{
homeNumber = value;
}
}
If countries to select a lot, to reduce the number of constructions If, I can advise to use the State pattern.
Advantages
simple solution
does not require third-party libraries and projects
Disadvantages
not a serious flaw, but the formatting of numbers is performed after the completion of printing numbers.
The definition of international phone numbers is a mess for 3 reasons:
1) How to dial an international phone number depends on the country you are in. If your application is used in only one country, then this is not too bad. However, there might be several ways how to get an international connection, like dialing first 00 or simply +.
2) The country code for a phone number is particularly bad designed. Just some examples:
1339 USA
1340 Virgin Islands (Caribbean Islands)
1341 USA
1342 not used
1343 Canada
The US, Canada and some smaller places share 1 as country code and the next 3 digits decide, if it is US or Canada or ... There is no easy way to figure out the country, like the first xxx are Canada, the rest US.
Some countries have a 2 digits code, others 3 and 4.
3) Even within the same country, different regions can have different formats.
The simplest solution is probably:
use a different format for international and national numbers
use for all internation numers the format +ccc dddddddd, where cc is a variable (!) length country code and dddddddd the digits within the country
depending on how many digits are used for dddddddd, you can write them as ddd dd dd, dddd dddd and ddd ddd ddd.
Of course, you can complicate it further by formatting also the area code within a country. I can't help you with areas, but for the rest you can find the code on Github (too much to post here):
github.com/PeterHuberSg/WpfWindowsLib/blob/master/WpfWindowsLib/PhoneTextBox.cs
A detailed explanation of international phone numbers and the PhoneTextBox is on CodeProject:
International Phone Number Validation Explained

Regex to help me break up Telephone numbers?

I have been tasked with the impossible, maybe?
I have a table with telephone numbers. But they are manually entered, and very dirty.
Example:
0711112399
07 1111 3288
07 1111 4832 NIKKI
0711117929
0711113616X123
0
NULL
1300 111 782
.
(Numbers changed to protect the innocent. :))
I need to break these into
CountryCode
AreaCode
Number
Extension
So, 0711112399 would become
CountryCode = +61 (Because there is no code on this number)
AreaCode = 07
Number = 11112399
Extension = NULL
11113616X123 would be
Country +61
AreaCode = NULL
Number = 11113616
Extension = 123
Rules are:
Possible area codes:
02 03 04 07 08
Is this even possible?
For 07 1111 4832 NIKKI - I will remove Alpha Numerics, unless it's an X between 2 numbers.
You can try this
^(00\d{2}|\+\d{2})?(0\d)?([\d ]+)(?:[xX](\d+))?
See it here on Regexr. You can see the content of the groups while hovering over the blue highlighted matches.
It will put the country code in Group1, the area code in group 2, the number in group 3 and the extension in group 4. All parts are optional except the number. When a part is not found, the value of the group is not set, you have to put your default values then.
I see a problem for the country code. It is hardcoded here with 2 digits, but I know there are also countries with a 3 digit code. For the countries with a 1 digit code, I am not sure, could be that there is a leading 0 then. But I need this to know when the area code/the number is starting.
I wouldn't say impossible but it will require rigorous testing. But I wouldn't necessarily focus on regular expressions. It may be simpler to implement using other techniques.
This is an ideal case to approach with Test Driven development. Start by listing all the possible cases, write a unit test for each case, and adjust the sanitizer code for the case.
There are dedicated libraries to normalize phone numbers, they're very specialized. But they tend to rely on Regex as well. The Lync Server (Microsoft's voice over ip solution), has a normalization library that relies on regex. Their page contains quite a few samples that will come in handy for you:
http://technet.microsoft.com/en-us/library/gg413082.aspx
In the end, it's probably easier to build a number of expressions that will normalize to a common format, than trying to create one expression to normalize everything.

Floating Point Number parsing: Is there a Catch All algorithm?

One of the fun parts of multi-cultural programming is number formats.
Americans use 10,000.50
Germans use 10.000,50
French use 10 000,50
My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10.
Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator.
The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser.
Does the .net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format?
I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again.
I don't know the ASP.NET side of the problem but .NET has a pretty powerful class: System.Globalization.CultureInfo. You can use the following code to parse a string containing a double value:
double d = double.Parse("100.20", CultureInfo.CurrentCulture);
// -- OR --
double d = double.Parse("100.20", CultureInfo.CurrentUICulture);
If ASP.NET somehow (i.e. using HTTP Request headers) passes current user's CultureInfo to either CultureInfo.CurrentCulture or CultureInfo.CurrentUICulture, these will work fine.
You can't please everyone. If I enter ten as 10.000, and someone enters ten thousand as 10.000, you cannot handle that without some knowledge of the culture of the input. Detect the culture somehow (browser, system setting - what is the use case? ASP? Internal app, or open to the world?), or provide an example of the expected formatting, and use the most lenient parser you can. Probably something like:
double d = Double.Parse("5,000.00", NumberStyles.Any, CultureInfo.InvariantCulture);
The difference between 12.345 in French and English is a factor of 1000. If you supply an expected range where max < 1000*min, you can easily guess.
Take for example the height of a person (including babies and children) in mm.
By using a range of 200-3000, an input of 1.800 or 1,800 can unambiguously be interpreted as 1 meter and 80 centimeters, whereas an input of 912.300 or 912,300 can unambiguously be interpreted as 91 centimeters and 2.3 millimeters.

Categories