Javascript to Format Phone Number

Posted: August 24, 2010 in ASP.Net, Javascript

If you need to format the Phone Number (NNN)NNN-NNNNxNNNNNN, you can use a little bit of Javascript with ASP.Net for when the user enters something in the text box control for example.

ASP.Net
First bind the onkeyup and onkeydown event to the text box control that you want to apply formatting on as follows:

 
' Add key events for phone numbers
txtPhoneNumber.Attributes.Add("onkeyup", "jsPhoneKeyUp(this,event);")
txtPhoneNumber.Attributes.Add("onkeydown", "jsPhoneKeyDown(this,event);")

Javascript
Now add the following Javascript code to the page that has the control to format:

 
<script type="text/javascript">
   //-----------------------------------------------
   // Global variables for phone number formatting.
   //-----------------------------------------------
   var lvChar = new Array(' ', '(', ')', '-', '.');
   var lvMaxPhoneLength = 20;
   var lvPhoneValue1;
   var lvPhoneValue2;
   var lvCursorPosition;
   //---------------------------------
   // Function to parse phone number.
   //---------------------------------
   function jsParseForNumber1(object)
   {
      lvPhoneValue1 = jsParseChar(object.value, lvChar);
   }
   //---------------------------------
   // Function to parse phone number.
   //---------------------------------
   function jsParseForNumber2(object)
   {
      lvPhoneValue2 = jsParseChar(object.value, lvChar);
   }
   //----------------------------------
   // Function to handle key up event.
   //----------------------------------
   function jsPhoneKeyUp(object,e)
   {
      if(e)
      {
          e = e;
      }
      else
      {
          e = window.event;
      }
      if(e.which)
      {
          var keycode = e.which;
      }
      else
      {
          var keycode = e.keyCode;
      }
      jsParseForNumber1(object);
      if(keycode >= 48)
      {
          jsValidatePhone(object);
      }
   }
   //------------------------------------
   // Function to handle key down event.
   //------------------------------------
   function jsPhoneKeyDown(object,e)
   {
      if(e)
      {
          e = e;
      }
      else
      {
          e = window.event;
      }
      if(e.which)
      {
          var keycode = e.which;
      }
      else
      {
          var keycode = e.keyCode;
      }
      jsParseForNumber2(object);
   }
   //--------------------------------------
   // Function to get the cursor position.
   //--------------------------------------
   function jsGetCursorPosition()
   {
      var lvPhone1 = lvPhoneValue1;
      var lvPhone2 = lvPhoneValue2;
      var lvBool = false;
      for (i = 0; i < lvPhone1.length; i++)
      {
          if (lvPhone1.substring(i,1) != lvPhone2.substring(i,1))
          {
              if(!lvBool)
              {
                  lvCursorPosition = i;
                  lvBool = true;
              }
          }
      }
   }
   //--------------------------------------------
   // Function to get validate the phone number.
   //--------------------------------------------
   function jsValidatePhone(object)
   {
      var lvPhone = lvPhoneValue1;
      lvPhone = lvPhone.replace(/[^\d*]/gi,"");
      if (lvPhone.length < 3)
      {
          object.value = lvPhone;
      }
      else if(lvPhone.length==3)
      {
          var lvPhoneCopy = lvPhone;
          var lvFirst = lvPhone.indexOf('(');
          var lvSecond = lvPhone.indexOf(')');
          if (lvFirst == -1)
          {
              lvPhoneCopy = "(" + lvPhoneCopy;
          }
          if (lvSecond == -1)
          {
              lvPhoneCopy = lvPhoneCopy + ")";
          }
          object.value = lvPhoneCopy;
      }
      else if (lvPhone.length > 3 && lvPhone.length < 7)
      {
          lvPhone ="(" + lvPhone;
          var lvPhoneLength = lvPhone.length;
          var lvSplit1 = lvPhone.substring(0,4);
          lvSplit1 = lvSplit1 + ")";
          var lvSplit2 = lvPhone.substring(4,lvPhoneLength);
          lvPhoneCopy = lvSplit1 + lvSplit2;
          object.value = lvPhoneCopy;
      }
      else if(lvPhone.length >= 7)
      {
          lvPhone = "(" + lvPhone;
          var lvPhoneLength = lvPhone.length;
          var lvSplit1 = lvPhone.substring(0,4);
          lvSplit1 = lvSplit1 + ")";
          var lvSplit2 = lvPhone.substring(4,lvPhoneLength);
          lvPhoneCopy = lvSplit1 + lvSplit2;
          var lvPhoneCopyLength = lvPhoneCopy.length;
          var lvPhoneCopySplit1 = lvPhoneCopy.substring(0,8);
          lvPhoneCopySplit1 = lvPhoneCopySplit1 + "-";
          if (lvPhoneCopyLength >= 13)
          {
              var lvPhoneCopySplit2 = lvPhoneCopy.substring(8,12);
              var lvPhoneExt = lvPhoneCopySplit1 + lvPhoneCopySplit2 + "x" + lvPhoneCopy.substring(12,lvPhoneCopyLength);
          }
          else
          {
              lvPhoneCopySplit2 = lvPhoneCopy.substring(8,lvPhoneCopyLength);
              lvPhoneExt = lvPhoneCopySplit1 + lvPhoneCopySplit2;
          }
          object.value = lvPhoneExt.substring(0, lvMaxPhoneLength);
      }
      jsGetCursorPosition();
      if(lvCursorPosition >= 0)
      {
          if (lvCursorPosition == 0)
          {
              lvCursorPosition = 2;
          }
          else if (lvCursorPosition <= 2)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          else if (lvCursorPosition <= 5)
          {
              lvCursorPosition = lvCursorPosition + 2;
          }
          else if (lvCursorPosition == 6)
          {
              lvCursorPosition = lvCursorPosition + 2;
          }
          else if (lvCursorPosition == 7)
          {
              lvCursorPosition = lvCursorPosition + 4;
              var lvEnd1 = object.value.indexOf(')');
              var lvEnd2 = object.value.indexOf('-');
              if (lvEnd1 >- 1 && lvEnd2 > -1)
              {
                  if (lvEnd2 - lvEnd1 == 4)
                  {
                      lvCursorPosition = lvCursorPosition - 1;
                  }
              }
          }
          else if (lvCursorPosition < 11)
          {
              lvCursorPosition = lvCursorPosition + 3;
          }
          else if (lvCursorPosition == 11)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          else if (lvCursorPosition >= 12)
          {
              lvCursorPosition = lvCursorPosition + 1;
          }
          var lvRange = object.createTextRange();
          lvRange.moveStart( "character", lvCursorPosition);
          lvRange.moveEnd( "character", lvCursorPosition - object.value.length);
          lvRange.select();
      }
   }
   //---------------------------------
   // Function to parse phone string.
   //---------------------------------
   function jsParseChar(asStr, asChar)
   {
      if (asChar.length == null)
      {
          lvChar = new Array(asChar);
      }
      else
      {
          lvChar = asChar;
      }
      for (i = 0; i < lvChar.length; i++)
      {
          lvNewStr = "";
          var lvStart = 0;
          var lvEnd = asStr.indexOf(asChar[i]);
          while (lvEnd != -1)
          {
              lvNewStr += asStr.substring(lvStart, lvEnd);
              lvStart = lvEnd + 1;
              lvEnd = asStr.indexOf(asChar[i], lvStart);
          }
          lvNewStr += asStr.substring(asStr.lastIndexOf(asChar[i]) + 1, asStr.length);
          asStr = lvNewStr;
      }
      return lvNewStr;
   }
</script>   
Advertisements
Comments
  1. Bilal Ahmed says:

    Thanks…..
    This code really help me …..
    Great efforts.

  2. Max says:

    Though the code is long, I must say it works in all kinds of situation. I have done intense testing on this.. works even on copy pasting invalid strings… Good job!

    P.S: I only wish I understood the code 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s