Format a phone number input while typing. (React JS).

December 26, 2020.
Thomas Duffy

Written by Thomas Duffy

react phone number input validation

Intro

In this post, I’ll show you how to create a phone number input field that formats and validates a US phone number while the user types.

Example of what we’ll build

phone-input-demo

Before we get too far

Today we are going to be implementing our phone number input using React JS. If you are looking for an example using just vanilla JS, you can find that post here.

Link to phone number input using vanilla JS

Set up

To make things simple and avoid going off into the left-field, I’m going to assume you don’t need help setting up React locally.

Start here

We’re going to start with a phoneInputComponent component that will be the basic skeleton for our input field. We’ll begin by having an onChange handler fire off and set the input value while the user types—something like this.

import React, { setState } from "react";

function phoneInputComponent() {
  const [inputValue, setInputValue] = useState("");

  const handleInput = (e) => {
    // this is where we'll call our future formatPhoneNumber function that we haven't written yet.
    const formattedPhoneNumber = formatPhoneNumber(e.target.value);
    // we'll set the input value using our setInputValue
    setInputValue(formattedPhoneNumber);
  };

  return <input onChange={(e) => handleInput(e)} value={inputValue} />;
}

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 then four digits
  // this is to avoid weird behavior that occurs if you  format the area code to 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, 10)}`;
}

Final code for phone number formatting input

Ok, that should do it. If you would like to play around with the above code, go ahead and check out the code sandbox.

react phone number input code

Conclusion on how to format and validate a phone number using React

I hope you enjoyed this post on how to format and validate a phone number using react. 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.


Thomas Duffy

Written by Thomas Duffy