Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoformat SSN while entering the number

Tags:

javascript

I have a textfield and the user enters the SSN number. While entering itself it should format. Like On the change of the textField... it should format 999-999-999 in this way on the display itself.

like image 634
John Cooper Avatar asked Oct 07 '11 09:10

John Cooper


2 Answers

@knod has the best answer here, but their solution had a drawback where folks couldn't type in their own dashes.

I modified their answer to allow users to (optionally) type or delete their own dashes and avoid blocking valid input (and added some comments to explain each step).

function formatSSN(ssn) {
  // remove all non-dash and non-numerals
  var val = ssn.replace(/[^\d-]/g, '');

  // add the first dash if number from the second group appear
  val = val.replace(/^(\d{3})-?(\d{1,2})/, '$1-$2');

  // add the second dash if numbers from the third group appear
  val = val.replace(/^(\d{3})-?(\d{2})-?(\d{1,4})/, '$1-$2-$3');

  // remove misplaced dashes
  val = val.split('').filter((val, idx) => {
    return val !== '-' || idx === 3 || idx === 6;
  }).join('');

  // enforce max length
  return val.substring(0, 11);
}

// bind our function
document.getElementById("ssn").onkeyup = function(e) {
  this.value = formatSSN(this.value);
}
like image 166
Karl Keefer Avatar answered Sep 19 '22 16:09

Karl Keefer


@Dennis's answer was the best here, however it used JQuery to do the selector and the OP did not have a JQuery tag on this post, just JavaScript. Here is the VanillaJS version of the solution (or at least one way to do it :)

document.getElementById("ssn").onkeyup = function() {
  var val = this.value.replace(/\D/g, '');
  var newVal = '';

  if(val.length > 4) {
    this.value = val;
  }

  if((val.length > 3) && (val.length < 6)) {
    newVal += val.substr(0, 3) + '-';
    val = val.substr(3);
  }

  if (val.length > 5) {
    newVal += val.substr(0, 3) + '-';
    newVal += val.substr(3, 2) + '-';
    val = val.substr(5);
  }

  newVal += val;
  this.value = newVal;
};
like image 24
Kris Boyd Avatar answered Sep 18 '22 16:09

Kris Boyd