0

I want to do a validate check to see if the SSN entered into a textbox follows this specific format: XXX-XX-XXXX as its being typed

I tried doing a function that just auto formats like this...

function ssnCheck() {
    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;
}

But it would bug out sometimes and not fully work especially on Mobile devices. I tried the solutions below, but they aren't working. The way I'm applying the above is by doing this..

document.getElementById("ssn").addEventListener('keyup',ssnCheck,false);

Any help on getting it to work so it auto formats as its being typed, or a better solution to this issue since it HAS to show in the XXX-XX-XXXX format when they are done typing in the box.

eqiz
  • 1,521
  • 5
  • 29
  • 51
  • 1
    Possible duplicate of [SSN Regex for 123-45-6789 OR XXX-XX-XXXX](http://stackoverflow.com/questions/4087468/ssn-regex-for-123-45-6789-or-xxx-xx-xxxx) – PM 77-1 Feb 09 '16 at 03:26
  • Just scan for 9 digits, and don't accept any other characters. Formatting is *your* responsibility. – Todd A. Jacobs Feb 09 '16 at 03:27
  • @PM77-1 I don't want a simple reg-ex I want it to happen as they are typing – eqiz Feb 09 '16 at 16:42
  • So you cannot just use a `pattern` attribute (or its poly-fill) like in [this answer](http://stackoverflow.com/a/21650828/2055998)? – PM 77-1 Feb 09 '16 at 19:30

1 Answers1

0

try this regax:

^\d{3}(?:[-]\d{2})(?:[-]\d{4})?$
  • ^ = Start of the string.
  • (?:…) = Grouping
  • \d{3} = Match 3 digits
  • \d{2} = Match 2 digits
  • \d{4} = Match 4 digits
  • [-] = Match a hyphen
  • $ = End of the string
Sinto
  • 3,915
  • 11
  • 36
  • 70