-1

I need to mask the SSN field as 123-45-6789 in React,

My aim is to do that without using plugings like react-input-mask,input-mask etc.

My input 123456789
Expected input 123-45-6789

Can we do that? By regex or something without plugings.

Any help would be appreciated.

user9074131
  • 63
  • 1
  • 3
  • 12

1 Answers1

4

You could use regular expressions to do it during the onChange event like this:

_onInputChange = (event) => {
    var string = event.target.value;
    string = string.replace(/-/g, "");
    var regex = /^([^\s]{3})([^\s]{2})([^\s]{4})$/g;
    var match = regex.exec(string);
    if (match) {
      match.shift();
      string = match.join("-")
    }
    this.setState({ssn: string});
}

Here's a working fiddle

However this will only mask the value after the whole number is typed out.

Jahl
  • 131
  • 1
  • 10