Home » Asp.net

Format phone number in asp.net textbox control


 I have a <asp:textbox> control, I want to display text as a phone number format like phone number mask.

Anybody can help on this. Thanks in advance.


11 Answers Found


Answer 1

Download the free ASP.NET Toolkit and use the masked edit box, there's a sample of the box

here : http://www.asp.net/AJAX/AjaxControlToolkit/Samples/MaskedEdit/MaskedEdit.aspx 

and the download page http://www.asp.net/AJAX/downloads/ 


Answer 2


I would like to know what should I download either "ajaxcontroltoolkit.zip" or  "ajaxcontrol toolkit-nosource.zip" from ajaxcontrolTOOLKIT with ajax extension1.0



Answer 3

ajaxcontroltoolkit.zip, it has a VS project in there with examples that you can look at


Answer 4

Any other idea with javascript


Answer 5


There are a bunch of examples if you search for "format phone  number + javascript"


Answer 6

Try this:

<script type="text/javascript">
String.prototype.replaceAll = function (replaceValue, newValue)
 var functionReturn = this;

 while ( true )
  var currentValue = functionReturn;

  functionReturn = functionReturn.replace(replaceValue, newValue);
  if ( functionReturn == currentValue )

 return functionReturn;
toTelephoneNumber = function (valueToFormat)
 var parsedValue = new String(valueToFormat);

 parsedValue = parsedValue.replaceAll('-', '');
 parsedValue = parsedValue.replaceAll('(', '');
 parsedValue = parsedValue.replaceAll(')', '');
 parsedValue = parsedValue.replaceAll(' ', '');

 if ( parsedValue.length >= 10 )
  var stringTemp = new String('');

  stringTemp = '(' + parsedValue.substr(0, 3) + ') ';
  stringTemp += parsedValue.substr(3, 3);
  stringTemp += '-';
  stringTemp += parsedValue.substr(6, 4);

  parsedValue = stringTemp;

 return parsedValue;

var formattedValue = toTelephoneNumber('1231231234');
// -->



Answer 7


Download the free ASP.NET Toolkit and use the masked edit box, there's a sample of the box

here : http://www.asp.net/AJAX/AjaxControlToolkit/Samples/MaskedEdit/MaskedEdit.aspx 

and the download page http://www.asp.net/AJAX/downloads/ 


The only reason I created an account was to tell you thank you so very much for your answer to this question. For the past few days I have been trying to figure out how to have a mask  in a text  field... and also what a mask was... and now with this links I was able to find out what I needed. 


Thank you. 


Answer 8

I followed this advice, downloaded and installed the Ajax controls.  A good number  of controls are now available, however the masked edit control  is not.  Not sure how to go about getting it.  Does anyone have any ideas? 


Answer 9

What version of ASP.NET/Visual Studio are you using?


Answer 10

Visual Studio 2008 Version 9.0.30729.1 SP

.NET Framework 3.5 SP1



Answer 11

This should get you what you need. This is exactly what I used to get it.

(asp.net/ajaxlibrary/act.ashx) (asp.net/ajaxlibrary/act_MaskedEdit.ashx)




Just in case, here is another link to something else.






I'm looking for a good asp.net Formating Phone number function (Not Javascript). 

I tried to take the one at http://dotnet.itags.org/webcontrols/93152/ and convert it to VB and it isn't working.


    Protected Function FormatPhone(ByVal strPhone As String)
        'This function formats a phone number
        strPhone = strPhone.Replace(" ", "").Replace(".", "").Replace("-", "").Replace("(", "").Replace(")", "")
        strPhone = strPhone.ToString
        Dim myPhone As Int64 = Convert.ToInt64(strPhone)

        Dim ret As String = Regex.Replace(myPhone, "(?<AreaCode>\d{3})(?<seg1>\d{3})(?<seg2>\d{4})", "(${AreaCode})-${seg1}-${seg2}")
        FormatPhone = ret
    End Function

I get an error:

Server Error in '/' Application.

Compilation Error 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: BC30519: Overload resolution failed because no accessible 'Replace' can be called without a narrowing conversion: 'Public Function Replace(input As String, replacement As String, count As Integer) As String': Argument matching parameter 'input' narrows from 'Long' to 'String'. 'Public Function Replace(input As String, replacement As String, count As Integer) As String': Argument matching parameter 'count' narrows from 'String' to 'Integer'. 'Public Shared Function Replace(input As String, pattern As String, replacement As String) As String': Argument matching parameter 'input' narrows from 'Long' to 'String'.

Source Error:


Line 653:        Dim myPhone As Int64 = Convert.ToInt64(strPhone)
Line 654:
Line 655:        Dim ret As String = Regex.Replace(myPhone, "(?<AreaCode>\d{3})(?<seg1>\d{3})(?<seg2>\d{4})", "(${AreaCode})-${seg1}-${seg2}")
Line 656:        FormatPhone = ret
Line 657:    End Function

So there is also an option of trying to fix this one...but I'm not married to it.

I know I can get information from a land-line number online, but is it possible to get a name and address from a cell phone number?. I have looked online and found websites who claim they can supply me with the details free of charge. But I am then always directed to a pay form. I do not mind paying a fee, but I do not want to be tricked into buying something. My view is, if these sites lied to me in the first place, just to get me on their site then how can I trust them any further. I mean if something is not free, then do not advertise it as being free!. Anyway enough rambling, back to my question. I guess what I need to know is, where can I reverse lookup a cell phone number from a legitimate source. I do not mind paying a fee as long as I receive the information I am looking for.


I've just installed Windows Phone developer tools beta on my Windows 7 Ultimate 64bits, and when I open a project that reference those assemblies it throws an error saying that they can be found.

I open that project with Visual Studio and Blend, and in both of them I get the same error.

How can I fix this error?


Insert html tage to sqlserver database through asp.net textbox

Display it lable control

Best regards


Hi @all,

knows anybody a tool which converts phone numbers to the correct "canonical address format". Which outlook is used?
see: http://support.microsoft.com/kb/949669/en-us

with kind regards

Matthias Back





I would like to format the phone number, fax, mobile phone and any other phone numbers entered to this format (xxx) xxx-xxxx.

What is the best way to handle this?



Hi Guys, 

i need to create a dynamic table asp.net (vb) datatable with textbox entry option,

what i have is, a access table with the parameter of

Columns : 10 or 16 (values can be change)  (10 =  has to create 10 cols, 16 = 16 cols, but please note that it can be any number) 


Rows :  5 or 10 

with the header text for each column, aslo i need to create a function to capture input data on a dynamic data-table in asp.net page. 

Please help 

kind Regards 



I am using CreateUserWizard control on my admin page.

After successfully creating a user with the control, it displays "Complete Your account has been successfully created."

After clicking on continue button it sets the ActiveStepIndex Correctly.

The problem is, while it sets the ActiveStepIndex correctly, it retains the old user account credentials.

Can any one help me.

Thanks in Advance


 My code behind is VB.NET. I use ASP.NET UpdatePanel like the following. However, after the post-back, all textbox in UpdatePanel won't accept any input, except when I move the mouse over and click on the TextBox.

Here's why I use UpdatePanel:

During the post-back, after inserting data into DB, set all TextBox text property to String.Empty

After the form is submitted, the Panel pStudent should be refresh , not the entire page

and the TextBox txtId is set in focus again.

It's very strange that this happened to me today. I used UpdatePanel before many time I never had such problem.

Can anyone show me why  all TextBox controls in UpdatePanel won't accept any input after the post-back even though the textbox is focused , only when you move mouse click in them? 

    <asp:UpdatePanel ID="upPOS" runat="server">
            <asp:Panel ID="pStudent" runat="server" CssClass="InContentInfoLight" 
        DefaultButton="btnSubmit" GroupingText="Cafeteria - POS">
                <br />
                <div class ="divleftcolumn-six">
                    ID Number :
                    <asp:TextBox ID="txtId" runat="server" AutoPostBack="True" 
            MaxLength="9" TabIndex="1" Height="24px" Width="150px" ValidationGroup="POS" 
                AutoCompleteType="Disabled" CssClass="numberOnly"></asp:TextBox>
                     <asp:Label ID="lblIdNotValidId" runat="server" CssClass="Mark-Red"></asp:Label>
                      <asp:Label ID="lblNameText" runat="server"></asp:Label>
                    <asp:Label ID="lblName" runat="server" CssClass="Mark-Green"></asp:Label>
                    <asp:Label ID="lblStatusText" runat="server"></asp:Label>
                     <asp:Label ID="lblStatus" runat="server"></asp:Label>
                    <br />
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
            ErrorMessage="* Please enter ID#" ValidationGroup="POS" Display="Dynamic">* Please enter ID#</asp:RequiredFieldValidator>
                    <br />
                    <br />
                    <asp:TextBox ID="txtValue" runat="server" MaxLength="4" TabIndex="2" 
            Height="24px" Width="150px" ValidationGroup="POS" CssClass="numberOnly"></asp:TextBox>
                     <asp:Button ID="btnSubmit" runat="server" TabIndex="3" Text="Submit" 
            ValidationGroup="POS" />
                     <asp:Label ID="lblInvalidValue" runat="server" CssClass="Mark-Red"></asp:Label>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
            ControlToValidate="txtValue" ErrorMessage="* Please enter some value" 
            Display="Dynamic" ValidationGroup="POS">* Please enter some value</asp:RequiredFieldValidator>
                    <br />
                <div class ="divrightcolumn-four">
                    <asp:Image ID="imgPhoto" runat="server" />
                    <asp:Label ID="lblMessage" runat="server" CssClass="Mark-Blue"></asp:Label>
                    <asp:Label ID="lblValue" CssClass ="mark-red-large" runat="server"></asp:Label>
                       <asp:ImageButton ID="btnUndo" runat="server" Height="40px" 
                             Width="36px" />
                <br />
                <br />
                <asp:HiddenField ID="hfLog" runat="server" />
                <br />
            <asp:AsyncPostBackTrigger ControlID="txtId" EventName="TextChanged" />
            <asp:AsyncPostBackTrigger ControlID="btnSubmit" EventName="Click" />


Thanks to Michal Bednarz (http://www.codetwo.com) and his post at EggHeadCafe, I was able to format all my contacts phone numbers the way I like. I know, perhaps not groundbreaking, lol, but there were enough people trying to do this in my search for the answer that I thought I'd throw this up to make someone else have it easier. My modifications and additions format phone numbers to: xxx-xxx-xxx, but the code can easily be tweaked to give you what you want.

One note, Outlook likes to auto-format phone numbers but I found several tips pointing to modifying the phone options in control panel - changing the area code to 99999, makes outlook stop putting the brackets around the area codes.

heres the code:

Sub FormatPhoneNumber()

Dim oFolder As MAPIFolder
Set oFolder = Application.ActiveExplorer.CurrentFolder
If Left(UCase(oFolder.DefaultMessageClass), 11) <> "IPM.CONTACT" Then
MsgBox "Select contact folder", vbExclamation
Exit Sub
End If

Dim nCounter As Integer
nCounter = 0

Dim oItem
For Each oItem In oFolder.Items
  Dim oContact As ContactItem
  Set oContact = oItem
  If Not oContact Is Nothing Then
    With oContact
      .AssistantTelephoneNumber = RemovePrefix(.AssistantTelephoneNumber)
      .Business2TelephoneNumber = RemovePrefix(.Business2TelephoneNumber)
      .BusinessFaxNumber = RemovePrefix(.BusinessFaxNumber)
      .BusinessTelephoneNumber = RemovePrefix(.BusinessTelephoneNumber)
      .CallbackTelephoneNumber = RemovePrefix(.CallbackTelephoneNumber)
      .CarTelephoneNumber = RemovePrefix(.CarTelephoneNumber)
      .CompanyMainTelephoneNumber = RemovePrefix(.CompanyMainTelephoneNumber)
      .Home2TelephoneNumber = RemovePrefix(.Home2TelephoneNumber)
      .HomeFaxNumber = RemovePrefix(.HomeFaxNumber)
      .HomeTelephoneNumber = RemovePrefix(.HomeTelephoneNumber)
      .ISDNNumber = RemovePrefix(.ISDNNumber)
      .MobileTelephoneNumber = RemovePrefix(.MobileTelephoneNumber)
      .OtherFaxNumber = RemovePrefix(.OtherFaxNumber)
      .OtherTelephoneNumber = RemovePrefix(.OtherTelephoneNumber)
      .PagerNumber = RemovePrefix(.PagerNumber)
      .PrimaryTelephoneNumber = RemovePrefix(.PrimaryTelephoneNumber)
      .RadioTelephoneNumber = RemovePrefix(.RadioTelephoneNumber)
      .TelexNumber = RemovePrefix(.TelexNumber)
      .TTYTDDTelephoneNumber = RemovePrefix(.TTYTDDTelephoneNumber)
      .AssistantTelephoneNumber = RemoveChars(.AssistantTelephoneNumber)
      .Business2TelephoneNumber = RemoveChars(.Business2TelephoneNumber)
      .BusinessFaxNumber = RemoveChars(.BusinessFaxNumber)
      .BusinessTelephoneNumber = RemoveChars(.BusinessTelephoneNumber)
      .CallbackTelephoneNumber = RemoveChars(.CallbackTelephoneNumber)
      .CarTelephoneNumber = RemoveChars(.CarTelephoneNumber)
      .CompanyMainTelephoneNumber = RemoveChars(.CompanyMainTelephoneNumber)
      .Home2TelephoneNumber = RemoveChars(.Home2TelephoneNumber)
      .HomeFaxNumber = RemoveChars(.HomeFaxNumber)
      .HomeTelephoneNumber = RemoveChars(.HomeTelephoneNumber)
      .ISDNNumber = RemoveChars(.ISDNNumber)
      .MobileTelephoneNumber = RemoveChars(.MobileTelephoneNumber)
      .OtherFaxNumber = RemoveChars(.OtherFaxNumber)
      .OtherTelephoneNumber = RemoveChars(.OtherTelephoneNumber)
      .PagerNumber = RemoveChars(.PagerNumber)
      .PrimaryTelephoneNumber = RemoveChars(.PrimaryTelephoneNumber)
      .RadioTelephoneNumber = RemoveChars(.RadioTelephoneNumber)
      .TelexNumber = RemoveChars(.TelexNumber)
      .TTYTDDTelephoneNumber = RemoveChars(.TTYTDDTelephoneNumber)

      nCounter = nCounter + 1
    End With
  End If

MsgBox nCounter & " contacts processed.", vbInformation

End Sub

Private Function RemovePrefix(strPhone As String) As String

strPhone = Trim(strPhone)
RemovePrefix = strPhone
If strPhone = "" Then Exit Function
Dim prefix As String
prefix = Left(strPhone, 1)

Do While (prefix = "+" Or prefix = "1")
  strPhone = Mid(strPhone, 2)
  prefix = Left(strPhone, 1)

RemovePrefix = strPhone

End Function

Private Function RemoveChars(strPhone As String) As String

strPhone = Trim(strPhone)
RemoveChars = strPhone
If strPhone = "" Then Exit Function
strPhone = Replace(strPhone, "(", "")
strPhone = Replace(strPhone, ")", "")
strPhone = Replace(strPhone, ".", "-")
strPhone = Replace(strPhone, " ", "-")
RemoveChars = strPhone

End Function


Patrick Freeman
...will work for cheap to get my foot in the door...


I am probably just super tired but can somebody tell me why my below code is not working?

Basically, what I am trying to do is replace the telephone number in correct format.

//the value here is the wrong format of telephone number
telephoneNumber = "507423-6262";
const string telephoneNumberRegex = @"\((?<AreaCode>\d{3})\)\s*(?<Number>\d{3}(?:-|\s*)\d{4})";

if (!Regex.IsMatch(telephoneNumber, telephoneNumberRegex))

//Remove all the non-numerics in the telephoneNumber.
telephoneNumber = Regex.Replace(telephoneNumber, "[^0-9]*", "");

string correctFormat = Regex.Replace(telephoneNumber, telephoneNumberRegex, @"(${AreaCode}) ${Number}-${4}");


Thanks a lot!


Dear Team,

is it possible when i typing numbers in textbox ,the textbox displying that numbers in this format..(000) 000-0000

the client wants to display the numbers when he typing in textbox the textbox displaying like that format..

is it posible are not i tried this one...

private void txtPhone_KeyDown(object sender, KeyEventArgs e)

    accpectingnumarics(sender, e);

if (txtPhone.Text.Length == 0)
                txtPhone.Text = "(" + txtPhone.Text;
                txtPhone.SelectionStart = txtPhone.Text.Length;
            if (txtPhone.Text.Length == 4)
                txtPhone.Text = txtPhone.Text + ")";
                txtPhone.SelectionStart = txtPhone.Text.Length;
            if (txtPhone.Text.Length == 5)
                txtPhone.Text = txtPhone.Text + " ";
                txtPhone.SelectionStart = txtPhone.Text.Length;
            if (txtPhone.Text.Length == 9)
                txtPhone.Text = txtPhone.Text + "-";
                txtPhone.SelectionStart = txtPhone.Text.Length;
            if (txtPhone.Text.Length == 10)
                txtPhone.Text = txtPhone.Text + " ";
                txtPhone.SelectionStart = txtPhone.Text.Length;
            txtPhone.SelectionStart = txtPhone.Text.Length;


but when client moves the mouse pointer in the middel of the textbox and delete some numbers and enter any numbers in that position then the cursor moves to end point...

please give me a suitable solutaion for this one...


 I have a repeater control and a link button outside of the repeater control.
I need to generate a textbox on every click on link button. I need 4 textbox on every row but only one textbox generate on every click. so after clicking 4 times , 4 textbox create in first row of the repeater and then create new textbox in the new row of the repeater. same for remove functionality.

Please suggest me.


I am trying to label the bars in my chart with a value.  The values are things like 23.4 representing 23.4% and so on.  I can use the following code to get the value there but I can't add a "%" character to the formatting.

Chart1.Series[mySeriesName].ChartType = SeriesChartType.Column;
Chart1.Series[mySeriesName].Points.DataBind(myDataView, "TheMonth", "UnissuedRate", "Label=UnissuedRate{0.0}");

The above code gets the UnissuedRate value correctly placed above the bar.  The problem is I would like to add a "%" so it shows up as "23.4%" instead of "23.4".

Using "Label=UnissuedRate{0.0%}" multiplies the values by 100 so I get "2340.0%" as the label.

Is there something like "Label=UnissuedRate{0.0}%" which would allow me more formatting of the value?


I apologize if this reveals how much of a rookie I am.

I'm trying to develop a webpage for a small college who want to keep the format similar to an existing webpage.  I've created an ASP.NET master page and included a menu (web.sitemap) to navigate the various pages of the school's site.  However, I'm trying to format the menu to match their existing old style html websites. 

I need to place a line between the various items of the menu.  I've tried border but I need the lines to appear above and below the items (or inbetween) and not on the left and right.  I've read that I may have to use CSS to format it the way I want but i can't figure out the code to so.  Could someone provide me a sample code of how this is done? 



I'm using wpf textbox in which users enter decimal numbers

what I want is when the text box loses focus to format the input in the following way:

suppose the user enteres 123456.45

then the displayed text should be 1,23,456.45



setting maxlength of asp.net textbox

maxlength set thr' properties not working  


Hi All,

  I want to know about masked edit textbox for phone number is any one please provide with example.....



Hello All,

I have a requirement where i need to access the methods of one user control in another user control.
Any pointers in this direction is greatly appreciated.

Thank you


I created a page with several controls (ddl, tbx) that I use for filtering a Gridview.  I created a javascript function that runs on the OnClientClick Event of an <asp:button  to set the value of an <asp:TextBox to today and a Selected Value in a ddl. 

function setMyToday() {
            var tbxToday = document.getElementById('ctl00_cntPage_tbxToday');
            var tbxUID = document.getElementById('ctl00_cntPage_tbxUserID');
            var ddlPV = document.getElementById('ctl00_cntPage_ddlProvider');
            tbxToday.value = makeToday();
            ddlPV.value = tbxUID.value;

The button submits the page and returns some records in a Gridview.  I can see the value in the tbxToday when the button is clicked and the row in the drop down list, but when the page is posted,the value in the text bos is lost and as a result is not used to filter the records.  However the value in the ddlProvider is maintained. 

What am I missing?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure