none
Format phone number

    Question

  • Hello,

    I have a text field where the user types in a telephone number. When the user is done typing the number and the text field loses its focus I need to take whatever the user typed and format it to a standard format. i.e. ###-###-####

    If a user types 1234567890  I need it to change to 123-456-7890.  Any ideas on how to do this or examples?

    Thanks!

    Sunday, January 08, 2006 11:01 PM

Answers

  • This is how to format a string of numbers into a proper phone number format. For example say a user types in the following for a phone number: 1234567890. The following code will take that value and turn it into this: 123-456-7890

     

    string x = txtPhone.Text;

    double y = Double.Parse(x);

    txtPhone.Text = String.Format("{0:###-###-####}", y);

    Tuesday, January 17, 2006 9:59 PM
  • The user will enter in different formats of a phone number. Two ways to do this is to either search the entire string for characters other then numbers, or to check the string and remove certain characters in their predeterimed spot. Here is an event that calls a method which will check to see if the user entered "(###) ###-####" or "#-###-###-####" or "##########" or "###-####". It will then fix it and return the format of "###-###-####".  Basically it works by assuming when someone is typing one of the given formats of a phone number it removes a character in the given position. So the number (###) ###-#### the (  ) are always in the position 0 & 4, so it removes whatever character is in that position. Again, it could be better, but at least it will help you when formatting numbers manually.

    Event that calls method

    private void btnPhone_Click(object sender, System.EventArgs e)

      {
       string x = txtPhone.Text;

         txtPhone.Text = Class1.formatPhone(x);
       }

    Method that checks and returns value

    public static string formatPhone(string x)

    {

    double y = 0;

    if (x.Length <= 8 || x.Length > 15)

    {

    MessageBox.Show("Your phone number does not contain the correct " +

    "number of digits. Please format number " +

    "as ###-###-####","Incorrect Number Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

    return x;

    }

    else

    {

    if (x.StartsWith("1-"))

    {

    x = x.Remove(0,1);

    x = x.Remove(0,1);

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    }

    if (x.Length == 14)

    {

    x = x.Remove(0,1);

    x = x.Remove(3,1);

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    y = Double.Parse(x);

    }

    else if (x.Length == 12)

    {

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    y = Double.Parse(x);

    }

    else if (x.Length == 10)

    {

    y = Double.Parse(x);

    }

    else

    {

    y = Double.Parse(x);

    }

    x = String.Format("{0:###-###-####}", y);

    return x;

    } //end else

    } //End public static string formatPhone(string x)

    Wednesday, January 18, 2006 7:05 PM

All replies

  • You want to create a control based on the textbox ( or add an event handler for lose focus in your main code ) and then reformat the string there.

     

    Monday, January 09, 2006 1:56 AM
  • Object Oriented Programming would have you create a PhoneNumber class...

    public class PhoneNumber

    {

       private string number = String.Empty;

       public string Number

       {

          get { return this.number; }

          set { this.number = value; }

       }

    }

    In the get and set methods of your PhoneNumber object's Number property, you can format the number as you need to see it.

    You can also override the built-in method for any class you design in .NET, called "ToString()" to return the Number formatted the way you wish.

    Take time to write the class and you get to take it with you...

    Monday, January 09, 2006 4:48 AM
  • Perhaps.  I'd be more inclined if I was to write a reusable class, to have one that can demand/enforce a variety of string formats.  Otherwise, you have 20 classes you move from project to project, which only differ very slightly from one another.

     

    Monday, January 09, 2006 4:51 AM
  •  cgraus wrote:

    Perhaps.  I'd be more inclined if I was to write a reusable class, to have one that can demand/enforce a variety of string formats.  Otherwise, you have 20 classes you move from project to project, which only differ very slightly from one another.

     

     

    Exactly!  That variety of string formats can be built up over time, as they are needed...

    It pays off to have a library of objects at hand for those times the .NET namespaces don't already have them written and ready to use.

    Monday, January 09, 2006 5:12 AM
  • If you're using using VS2005, you can just used a "Masked Text Box" and set its mask to "Phone Number", or enter your own mask. That will format things as you enter them - much nicer.

    If you're using VS2003, well, that's so last year. 

    Monday, January 09, 2006 3:31 PM
  • haha, yes I have heard about that new feature in VS 2005.

    My problem is getting it to format the string. This is what I have:

    string convert = txtPhone.Text;

    String.Format("{0:(###) ###-####}", convert);

    txtPhone.Text = convert;

    but, the numbers never change once the code executes! I know I am probably jacking the format syntax up, but I couldn't find any good examples anywhere.

    Thanks!

    ~zero

    Monday, January 09, 2006 8:04 PM
  • If you're using a Masked Text Box, it will format the string for you.
    For example, if you have set the mask to something like this:

    this.maskedTextBox1.Mask = "(999) 000-0000";


    then when you assign the string "1234567890" to the masked text box's text like so:

    this.maskedTextBox1.Text = "1234567890";

    the text will be displayed as "(123) 456-7890"
    Unfortunately, string.Format() won't format strings like that.
    Tuesday, January 10, 2006 9:29 AM
  • Since I do not have the 2005 version of VS; how would it be done in VS 2003 with C#?

    How can I take their phone number and format it? Can you provide an example code?

     

    Thursday, January 12, 2006 8:26 PM
  • www.codeproject.com is bound to have an example, but basically, you should do what I said in the first place, you can parse the string yourself and then format it, probably in the event raised when the textbox loses focus.  You can use regular expressions for this.  If you don't have it, Expresso is a great tool for working with regex, it's on the CP site as well.

     

     

    Thursday, January 12, 2006 9:54 PM
  • The ActiveX MaskedEditBox is available in VS.NET 2003, but this IS a .NET 2.0-specific forum you know.  Of course people will normally answer questions on .NET 1.x but you really should stipulate that that's what you're using from the word go.
    Sunday, January 15, 2006 12:35 PM
  •  jmcilhinney wrote:
    The ActiveX MaskedEditBox is available in VS.NET 2003, but this IS a .NET 2.0-specific forum you know.  Of course people will normally answer questions on .NET 1.x but you really should stipulate that that's what you're using from the word go.

    Where does is say that this is a .NET 2.0-specific forum? This is a C#-forum, actually, and not bound to any particular version of .NET.

    Sunday, January 15, 2006 12:58 PM
  • Yeah, that's true!


    Nevertheless, I think the default stance in most forums is to assume the latest version, unless otherwise directed. Otherwise you end up asking "which version of C#/.net?" for almost every question...

    Therefore, as an example, if someone asks a question that could be solved using generics, someone else will probably suggestan answer that uses generics - unless the OP stipulates C# version 1 in the question.

    I must further point out that the description of this forum says "Issues regarding the C# language and compiler – including things like generics, anonymous methods, etc."

    Note the use of the term "generics" in the description - which most certainly implies C# 2!

    Monday, January 16, 2006 9:52 AM
  • This is how to format a string of numbers into a proper phone number format. For example say a user types in the following for a phone number: 1234567890. The following code will take that value and turn it into this: 123-456-7890

     

    string x = txtPhone.Text;

    double y = Double.Parse(x);

    txtPhone.Text = String.Format("{0:###-###-####}", y);

    Tuesday, January 17, 2006 9:59 PM
  • The user will enter in different formats of a phone number. Two ways to do this is to either search the entire string for characters other then numbers, or to check the string and remove certain characters in their predeterimed spot. Here is an event that calls a method which will check to see if the user entered "(###) ###-####" or "#-###-###-####" or "##########" or "###-####". It will then fix it and return the format of "###-###-####".  Basically it works by assuming when someone is typing one of the given formats of a phone number it removes a character in the given position. So the number (###) ###-#### the (  ) are always in the position 0 & 4, so it removes whatever character is in that position. Again, it could be better, but at least it will help you when formatting numbers manually.

    Event that calls method

    private void btnPhone_Click(object sender, System.EventArgs e)

      {
       string x = txtPhone.Text;

         txtPhone.Text = Class1.formatPhone(x);
       }

    Method that checks and returns value

    public static string formatPhone(string x)

    {

    double y = 0;

    if (x.Length <= 8 || x.Length > 15)

    {

    MessageBox.Show("Your phone number does not contain the correct " +

    "number of digits. Please format number " +

    "as ###-###-####","Incorrect Number Format", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

    return x;

    }

    else

    {

    if (x.StartsWith("1-"))

    {

    x = x.Remove(0,1);

    x = x.Remove(0,1);

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    }

    if (x.Length == 14)

    {

    x = x.Remove(0,1);

    x = x.Remove(3,1);

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    y = Double.Parse(x);

    }

    else if (x.Length == 12)

    {

    x = x.Remove(3,1);

    x = x.Remove(6,1);

    y = Double.Parse(x);

    }

    else if (x.Length == 10)

    {

    y = Double.Parse(x);

    }

    else

    {

    y = Double.Parse(x);

    }

    x = String.Format("{0:###-###-####}", y);

    return x;

    } //end else

    } //End public static string formatPhone(string x)

    Wednesday, January 18, 2006 7:05 PM
  • ...or you could handle any possible input format generically as follows:

            public static string ParsePhoneNumber(string origPhoneNumber)
            {
                StringBuilder sb = new StringBuilder();
                foreach (char c in origPhoneNumber.ToCharArray())
                {
                    if (char.IsDigit(c))
                    {
                        sb.Append(c);
                    }
                }
                return sb.ToString();
            }

    This returns only the digits, stripping all letters and special characters.  You can then simply and accurately validate for length, depending on what you want to accept.  Digit-only is the ideal format for storage, and then you can format it however you want when displaying it back to the user. 

    If you wanted to get really fnacy you could modify this routine to also accept letters (char.IsLetter(c)) and automatically convert them to the corresponding digits.  However, this gets messy if you want to support international character sets -- if you don't care about that, it could add additional input flexibility.
    Friday, February 17, 2006 7:37 AM
  • Here's another alternative - create your own formatter to be used with the IFormatProvider interface.

     

    public class PhoneNumber : ICustomFormatter, IFormatProvider

    {

    #region IFormatProvider Members

    public object GetFormat(Type formatType)

    {

    if (formatType == typeof(ICustomFormatter))

    return this;

    else return null;

    }

    #endregion

    #region ICustomFormatter Members

    public string Format(string format, object arg, IFormatProvider formatProvider)

    {

    if (arg == null || !(arg is string) || arg.ToString().Length == 0 || !char.IsDigit(arg.ToString()[0]))

    {

    if (arg is IFormattable) return ((IFormattable)arg).ToString(format, formatProvider);

    else return arg.ToString();

    }

    format = arg.ToString();

    switch (format.Length)

    {

    case 7: // format as 7-digit phone number

    format = OnlyDigits(format);

    return format.Substring(0, 3) + "-" + format.Substring(3);

    case 10:

    format = OnlyDigits(format);

    return String.Format("({0}) {1}-{2}",

    format.Substring(0, 3), format.Substring(3, 3), format.Substring(6));

    case 11:

    format = OnlyDigits(format);

    return String.Format("{0} ({1}) {2}-{3}",

    format.Substring(0, 1), format.Substring(1, 3), format.Substring(4, 3), format.Substring(7));

    default:

    return format;

    //throw new ArgumentException("Unknown input string '" + format + "'", "format");

    }

    }

    #endregion

    private string OnlyDigits(string input)

    {

    string retVal = "";

    for (int i = 0; i < input.Length; i++)

    {

    if (char.IsDigit(inputIdea)) retVal += inputIdea;

    }

    return retVal;

    }

    }

     

    Now use this in conjunction with String.Format

    Friday, April 14, 2006 3:39 PM
  • There are too many formats to take into account when filtering out unwanted characters.  The best approach is to remove all non numeric characters first.

     

    string rawPhoneNumber = "1234567890";

    string y = "";

    // Strip out all non numeric values from the string

    foreach (char c in rawPhoneNumber)

    {

    if ((int) c > 47 && (int) c < 58)

    {

     // Add the numeric chars to the string

    y += c.ToString();

    }

    }

     

    Now do the formatting if the length of the string = 10

    if (y.Length == 10) ...

     

    x = String.Format("{0[:#]##-###-####}", Double.Parse(y));  or

    x = String.Format("{0Sad###) ###-####}", Double.Parse(y)); or

    x = String.Format("{0[:#]##.###.####}", Double.Parse(y));  etc.

     

     

    Wednesday, May 07, 2008 7:03 PM
  • One variation on this is to use Regex to remove non-numeric characters. This makes the code a bit cleaner and performs better. The example provided below illustrates how to do this and allows for phone numbers to be normalized within a string that may contain other data without harming that other data. The code below will detect just about any cultured phone number format and normalize to US format.

     

    -James.F

     

     

     

    public static string FormatUSPhoneNumberOccuranceWithinString(string rawData)       
    {
        System.Text.RegularExpressions.Regex rg = new Regex(@"((\(\d{3}\)?)|(\d{3}))([\s-./]?)(\d{3})([\s-./]?)(\d{4})");
        System.Text.RegularExpressions.Match m = rg.Match(rawData);

        if (m != null)
        {
            string numberChars = ExtractNumberChars(m.Value);
            ulong numbers;
            if (ulong.TryParse(numberChars, out numbers))
            {
                return rawData.Replace(m.Value, String.Format("{0Sad###) ###-####}", numbers));
            }
            else
            {
                return rawData;
            }
        }
        else
        {
            return rawData;
        }
    }

    public static string ExtractNumberChars( string p_DirtyString )
    {
       return processReplaceRegex( p_DirtyString, "[^0-9]", "" ); // extract numbers.
    }

    public static string processReplaceRegex( string p_strIn, string p_regXP, string p_strReplaceWith )
    {
      System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex( p_regXP );
      return System.Text.RegularExpressions.Regex.Replace( p_strIn, p_regXP, p_strReplaceWith );
    }

     

    }

    }

    Monday, September 15, 2008 7:33 PM