Format a phone number input while typing in Javascript.

November 29, 2020.

Written by Thomas Duffy

Intro

Formatting and validating a phone number in Javascript is a pretty common task when implementing things like checkout or a contact form. This post will show you how to create a phone input field that formats and validates a US phone number while the user types.

Example of what we’ll build

phone-input-demo

Start with the markup

The first thing we’re going to do is to start creating our input field. To avoid making this post specific to any particular library, I will write my example using plain old HTML and Javascript.

Let’s start with some markup where the input field will live. We’ll also add the id attribute with a value of “phone-number” to hook up our formatting function later.

<!DOCTYPE html>
<html>
  <body>
    <input id="phone-number" />
  </body>
</html>

Add the handler and script tag for some JS

Now, let’s add the script tag where the formatting function will live. We’ll also be adding the onkeydown event handler to the input element to fire off the formatting function while typing the phone number in the input field.

<!DOCTYPE html>
<html>
  <body>
    <input onkeydown="phoneNumberFormatter()" id="phone-number" />
  </body>
  <script>
    // JS to format phone number
  </script>
</html>

Create onkeydown handler to hook up format function

Next, let’s start by writing the phoneNumberFormatter function.

function phoneNumberFormatter() {
  // grab the value of what the user is typing into the input
  const inputField = document.getElementById('phone-number');

  // next, we're going to format this input with the `formatPhoneNumber` function, which we'll write next.
  const formattedInputValue = formatPhoneNumber(inputField.value);

  // Then we'll set the value of the inputField to the formattedValue we generated with the formatPhoneNumber
  inputField.value = formattedInputValue;
}

Write custom format function to validate and format phone number input

So the above function hooks onto the input element and passes the value into our future custom formatPhoneNumber function, then sets the input elements value to the new formatted value.

Now, let’s write our custom formatPhoneNumber function.

function formatPhoneNumber(value) {
  // if input value is falsy eg if the user deletes the input, then just return
  if (!value) return value;

  // clean the input for any non-digit values.
  const phoneNumber = value.replace(/[^\d]/g, '');

  // phoneNumberLength is used to know when to apply our formatting for the phone number
  const phoneNumberLength = phoneNumber.length;

  // we need to return the value with no formatting if its less than four digits
  // this is to avoid weird behavior that occurs if you  format the area code too early
  if (phoneNumberLength < 4) return phoneNumber;

  // if phoneNumberLength is greater than 4 and less the 7 we start to return
  // the formatted number
  if (phoneNumberLength < 7) {
    return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
  }

  // finally, if the phoneNumberLength is greater then seven, we add the last
  // bit of formatting and return it.
  return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
    3,
    6
  )}-${phoneNumber.slice(6, 9)}`;
}

Final code for phone number formatting input

Ok, now your markup should look like something below.

<!DOCTYPE html>
<html>
  <body>
    <input onkeydown="phoneNumberFormatter()" id="phone-number" />

    <script>
      function formatPhoneNumber(value) {
        if (!value) return value;
        const phoneNumber = value.replace(/[^\d]/g, '');
        const phoneNumberLength = phoneNumber.length;
        if (phoneNumberLength < 4) return phoneNumber;
        if (phoneNumberLength < 7) {
          return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
        }
        return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
          3,
          6
        )}-${phoneNumber.slice(6, 9)}`;
      }

      function phoneNumberFormatter() {
        const inputField = document.getElementById('phone-number');
        const formattedInputValue = formatPhoneNumber(inputField.value);
        inputField.value = formattedInputValue;
      }
    </script>
  </body>
</html>

Conclusion on how to format and validate a phone number

I hope you enjoyed this post on formatting and validating a phone number using vanilla Javascript. If you like this post, please sign up for my newsletter, where you can be notified when I drop new posts related to frontend web development.


Written by Thomas Duffy

Want to Build animations like the one above?

Sign up and get notified when I release my mini course on building animations with React.