JavaScript Format Phone Number – Dead Simple

Recently I needed to roll my own phone number formatting for a problem at work.  The basic requirement was as follows:

  • All the user to only enter numbers, no other characters were allowed
  • The user could only enter 10 numbers
  • After all the numbers were entered, the value would auto-format to (xxx)-xxx-xxxx
  • The user could backspace over the numbers to change the value

Maybe I just didn’t look long enough but I didn’t find anything quickly that would do this so I made my own.  Here is how I did it.

HTML

Pretty standard stuff here.  Just some Bootstrap layout and wiring for the JS.


<body>
  <div class="row">
    <div class="col-md-6">
      <div class="form-group">
        <label class="col-md-5" for="phoneNumber">Enter your phone number</label>
        <div class="col-md-6">
          <input id="phoneNumber" name="phoneNumber" type="text" class="form-control input-md" onkeypress="return isNumber(event)" onkeyup="setPhoneFormat(this)" maxlength="14"/>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <div class="form-group">
        <label class="col-md-5" for="phoneNumber">Enter alternate phone number</label>
        <div class="col-md-6">
          <input id="phoneNumberAlt" name="phoneNumberAlt" type="text" class="form-control input-md" onkeypress="return isNumber(event)" onkeyup="setPhoneFormat(this)" maxlength="14"/>
        </div>
      </div>
    </div>
  </div>
</body>

CSS

Basic CSS just to play around with a quick layout for debugging.


body {
  margin: 120px auto;
  width: 300px;
}

JS


function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

function setPhoneFormat(src) {
		var x = src.value;
    x = x.replace(/[^0-9]/g, "");
    
    //console.log('stripped x says: ' + x);
    
    if (x.length == 10) {
    	var areaCode = x.substr(0,3);
      var exchangeNum = x.substr(3,3);
      var phoneNum = x.substr(6,4);
      src.value = "(" + areaCode + ") " + exchangeNum + "-" + phoneNum;
    }
}

The “magic” happens here.  Essentially this is just two functions:

  • isNumber: keeps the user from typing anything except numbers and the backspace key.
  • setPhoneFormat: formats the phone number once 10 characters have been reached and updates the referenced control.

Give it a shot!  Here is a link to a JSFiddle for this too.

Worked well enough for what we needed at the time even though I want to make the following tweaks.

  • Format the text AS the user types it in rather than waiting for 10 characters to be reached before formatting.
  • Allow the user to change a character anywhere within the string, rather than having to backspace from the end to where they want to edit.

Minor things, I know but us coders are always tweaking!

Did you enjoy this article?
Signup today and receive free updates straight in your inbox. We will never share or sell your email address.
I agree to have my personal information transfered to MailChimp ( more information )
Powered by Optin Forms