views:

58

answers:

3

I am storing phone numbers of varying lengths in my WPF (C#, VS 08) App.

I store them as strings. My question is about my method AddNewPhoneNo(string phoneNo).

In this method, I use Int.TryParse to validate the incoming number (i.e. not null, is numeric...). I've since realized this is probably not the best way to do this, because then I am limited to a number which is ± 2147483647. Definetly this is not always the case with phone numbers.

What is a good, easy way to validate phone numbers? I guess the basic rules would be as follows:

  • All numeric
  • All positive
  • Upto 25 chars (could be more, but this will to do for time being)

Can't thing if theres any more rules at the moment, that's probably it.

+1  A: 

How about a RegEx pattern: http://regexlib.com/REDetails.aspx?regexp_id=458

Adam Driscoll
I guess so, I had been told to avoid these but guess it may be simplest and easiest method
baron
@baron - RegEx can be confusing and hard to debug but I think for this type of well known pattern (and already existent RegEx) it's pretty safe to say it's probably the best method.
Adam Driscoll
+1  A: 

You could try Int64.TryParse which would give you a range of ±9223372036854775807

Keivan
+1  A: 

If your constraints are that the string must be not-null, nothing but numbers, and <= 25 chars, then you can simply do the following:

static bool IsValidPhoneNumber(string phoneNumber)
{
    return !string.IsNullOrEmpty(phoneNumber)
        && (phoneNumber.Length <= 25)
        && phoneNumber.All(c => char.IsNumber(c));
}

If your constraints are more complex (e.g. the string can contain digit grouping like "123-456-7890" or parenthesis like "(123)4567890") then you should go with RegEx.

Chris Schmich