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.
@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);
}
@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;
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With