Insert space between numbers in Textbox

Total Post:45

C#  .NET 
 1411  View(s)
Rate this:

I have this TextBox where a user can type in his/her Phone number.


<asp:TextBox runat="server" ID="txtPhone" CssClass="TicketField FieldWidthH txtboxStyle" />

If the user types 12345678 I would like it to auto "show" 12 34 56 78 so there is a space after each 2 numbers. 

Here is my C# code: 

if (IsPostBack) {
    if (!string.IsNullOrEmpty(txtPhone.Text)) {
        // Check if the value contains any non-numeric values and strip them out
        string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, @"^\d{6}$", "");
         // Parse your number as an integer from your TextBox (after cleaning it up)
         Int64 yourIntegerTextBoxValue = Int64.Parse(cleanedUpTextBoxValue);
         // Format your number as a string
         string formattedResult = yourIntegerTextBoxValue.ToString("## ## ## ##");
         // Output the result into your TextBox
         txtPhone.Text = formattedResult;
I also tried string cleanedUpTextBoxValue = Regex.Replace(txtPhone.Text, "[^\d]", "");

But then I type in the Textbox I still only displays the numbers as 12345678.

What am i doing wrong?

Thanks for your time

  1. Post:30

    Re: Insert space between numbers in Textbox

    I'd generally recommend using JavaScript for this if possible, but if you want a C# solution, you can use this to strip out non-digit characters:


    string text = Regex.Replace(txtPhone.Text, @"\D", "");

    And then this to insert spaces around each pair of digits:


    text = Regex.Replace(text, @"\d\d(?!$)", "$0 ");

    txtPhone.Text = text;

    If implemented in JavaScript, it would look a little bit like this:


    text = text.replace(/\D/g, '').replace(/(\d\d)(?!$)/g, '$1 ')

  1. Post:45

    Re: Insert space between numbers in Textbox

    Use the Insert method of string.


    string phone = txtPhone.Text; // or your cleaned-up string

    phone = phone.Insert(2, " ");

    txtPhone.Text = phone;

    You can put a loop in there to get spaces between every other digit as needed. Looping over the length of the string, starting from the end, is probably the easiest. Check the length of the string to determine your starting position (i.e., the last character or next to last).