Format a US SSN input while typing with ReactJS.

January 19, 2022.

Written by Thomas Duffy

ssn input validation

Intro

We’ll create an input field that formats a US social security number (SSN) in this post. This post will be React specific. If you would like to see how to write this in plain vanilla Javascript you can read this post where the examples are written in vanilla JS and HTML.

Link to SSN input using vanilla JS

Example of what we’ll build

ssn-input-demo

Set up

To stay focused on the topic of this post, I’m going to assume you don’t need help setting up React locally.

Start here

We’re going to start with a ssnInputComponent component that will be our input field. We’ll begin by having an onChange handler fire off and set the input value while the user types.

export default function ssnInputComponent() {
  const [inputValue, setInputValue] = useState('');

  const handleInput = (e) => {
    // this is where we'll call the formatSSN function
    const formattedSSN = formatSSN(e.target.value);
    // we'll set the input value using our setInputValue
    setInputValue(formattedSSN);
  };

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

Now, let’s write our custom formatSSN function.

function formatSSN(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 ssn = value.replace(/[^\d]/g, '');

  // ssnLength is used to know when to apply our formatting for the ssn
  const ssnLength = ssn.length;

  // we need to return the value with no formatting if its less then four digits
  if (ssnLength < 4) return ssn;

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

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

Final code for ssn number formatting input

If you would like to play around with the above code, go ahead and check out the code sandbox.

react ssn number input code

Conclusion on how to format and validate an SSN using React

I hope you enjoyed this post on how to format and validate an SSN using reactJS. 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 and programming.


Written by Thomas Duffy

Popular Posts

9 ways you can be a better programmer
Join my newsletter

Get web dev videos, posts, and tips in your inbox