Validate a US Social Security number in JavaScript
Intermediate · 3 min read
A US Social Security number (SSN) is nine digits written in three groups: 123-45-6789. Payroll systems, tax forms and loan applications ask for it. A pattern check catches typos before the form is sent, and it can also refuse number ranges that have never been issued.
That second part teaches one of the most useful regex tools: the negative lookahead. It lets you say "anything except these few values" without listing every allowed value. You will also write a mask, because an SSN should almost never be shown in full. You need to know /.../.test(), ^, $ and \d{3}. Lookaheads are explained from zero.
The rules
The three groups are called the area (3 digits), the group (2 digits) and the serial (4 digits). Some values are never issued:
- area
000,666, or anything from900to999 - group
00 - serial
0000
What a lookahead is
Most of a pattern consumes text: \d matches a digit and moves past it. A lookahead only peeks at what comes next, then stays where it was.
(?!...) is a negative lookahead. It means "the next characters must NOT be this". It doesn't use up any characters, so the next part of the pattern still sees them:
const notCat = /^(?!cat)[a-z]{3}$/;
console.log(notCat.test('dog')); // true
console.log(notCat.test('cat')); // false
(?!cat) checks the start isn't cat. Then [a-z]{3} matches the three letters as usual.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
15 Validate a social security number
fairCheck a US social security number. It is nine digits in three groups, and several ranges are never issued.
Stuck? Three hints, smallest first
- 1. The shape is
123-45-6789: three digits, two, then four. - 2. Never issued: area
000,666, or anything from900up; group00; serial0000. - 3. A negative lookahead,
(?!000|666|9\d\d), excludes those without listing every valid value.
Step 1: just the shape
Three digits, a dash, two digits, a dash, four digits:
const SHAPE = /^\d{3}-\d{2}-\d{4}$/;
console.log(SHAPE.test('123-45-6789')); // true
console.log(SHAPE.test('123456789')); // false: no dashes
console.log(SHAPE.test('000-45-6789')); // true, but area 000 is never issued
Step 2: exclude the bad areas
Put a negative lookahead in front of the area. 9\d\d covers every number from 900 to 999, and | means "or":
const AREA_OK = /^(?!000|666|9\d\d)\d{3}$/;
console.log(AREA_OK.test('123')); // true
console.log(AREA_OK.test('899')); // true
console.log(AREA_OK.test('000')); // false
console.log(AREA_OK.test('666')); // false
console.log(AREA_OK.test('900')); // false
Listing the bad values takes three short pieces. Listing all the good ones would take hundreds. That is why lookaheads are worth learning.
Step 3: exclude the bad group and serial
The same trick works in front of the other two parts:
const SSN = /^(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/;
const isSsn = (value) => typeof value === 'string' && SSN.test(value);
console.log(isSsn('123-45-6789')); // true
console.log(isSsn('001-01-0001')); // true: the lowest valid number
console.log(isSsn('123-00-6789')); // false
console.log(isSsn('123-45-0000')); // false
console.log(isSsn('123-01-6789')); // true
Each lookahead sits right before the part it guards, so it peeks at exactly those digits.
Step 4: accept numbers without dashes
People often type the nine digits with no dashes. -? makes each dash optional. After checking, rebuild the dashed form with slice:
const SSN_LOOSE = /^(?!000|666|9\d\d)\d{3}-?(?!00)\d{2}-?(?!0000)\d{4}$/;
function normaliseSsn(value) {
if (typeof value !== 'string' || !SSN_LOOSE.test(value)) return null;
const d = value.replace(/-/g, '');
return `${d.slice(0, 3)}-${d.slice(3, 5)}-${d.slice(5)}`;
}
console.log(normaliseSsn('123456789')); // '123-45-6789'
console.log(normaliseSsn('666456789')); // null: area 666
Step 5: mask it for display
An SSN is very sensitive. Show only the last four digits, the way bank statements do:
const SSN = /^(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/;
const isSsn = (value) => typeof value === 'string' && SSN.test(value);
const mask = (ssn) => (isSsn(ssn) ? `***-**-${ssn.slice(-4)}` : null);
console.log(mask('123-45-6789')); // '***-**-6789'
console.log(mask('000-45-6789')); // null
slice(-4) takes the last four characters.
The full solution
The panel runs a list of numbers through the strict pattern, tidies one without dashes, and masks a valid one. Press Run and check both sides of each boundary: 899 passes, 900 doesn't.
/* (?!...) is a negative lookahead: "the next characters must NOT match this",
and it consumes nothing. It is how you exclude a few cases from a range
instead of enumerating the thousands that remain. */
const SSN = /^(?!000|666|9\d\d)\d{3}-(?!00)\d{2}-(?!0000)\d{4}$/;
const isSsn = (value) => typeof value === 'string' && SSN.test(value);
// Also accepting the unpunctuated form, then normalising.
const SSN_LOOSE = /^(?!000|666|9\d\d)\d{3}-?(?!00)\d{2}-?(?!0000)\d{4}$/;
function normaliseSsn(value) {
if (typeof value !== 'string' || !SSN_LOOSE.test(value)) return null;
const d = value.replace(/-/g, '');
return `${d.slice(0, 3)}-${d.slice(3, 5)}-${d.slice(5)}`;
}
// Masking, which is what you should almost always show instead of the number.
const mask = (ssn) => (isSsn(ssn) ? `***-**-${ssn.slice(-4)}` : null);
const cases = ['123-45-6789', '001-01-0001', '000-45-6789', '666-45-6789',
'900-45-6789', '999-45-6789', '123-00-6789', '123-45-0000', '123456789',
'12-345-6789', '', '123-45-678'];
for (const s of cases) console.log(JSON.stringify(s).padEnd(14), isSsn(s));
console.log('unpunctuated normalises:', normaliseSsn('123456789'));
console.log('masked for display :', mask('123-45-6789'));
Output
20 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 20 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a valid number passes', isSsn('123-45-6789'), true);
test('the lowest valid combination', isSsn('001-01-0001'), true);
test('area 000 is never issued', isSsn('000-45-6789'), false);
test('area 666 is never issued', isSsn('666-45-6789'), false);
test('area 900 and above is never issued', isSsn('900-45-6789'), false);
test('including 999', isSsn('999-45-6789'), false);
test('but 899 is fine', isSsn('899-45-6789'), true);
test('group 00 is never issued', isSsn('123-00-6789'), false);
test('but 01 is', isSsn('123-01-6789'), true);
test('serial 0000 is never issued', isSsn('123-45-0000'), false);
test('but 0001 is', isSsn('123-45-0001'), true);
test('the dashes are required by the strict pattern', isSsn('123456789'), false);
test('groups of the wrong length are refused', isSsn('12-345-6789'), false);
test('too few digits are refused', isSsn('123-45-678'), false);
test('an empty string is refused', isSsn(''), false);
test('the loose pattern accepts no dashes', SSN_LOOSE.test('123456789'), true);
test('and normalises it', normaliseSsn('123456789'), '123-45-6789');
test('while still refusing an excluded area', normaliseSsn('666456789'), null);
test('masking shows only the last four', mask('123-45-6789'), '***-**-6789');
test('and refuses an invalid number', mask('000-45-6789'), null);
The negative lookahead (?!000|666|9dd) is the technique worth learning here. It asserts what must not come next and consumes nothing, so d{3} still does the matching. Excluding three cases this way is far shorter than enumerating the 897 that remain, and the assertions check both sides of each boundary — 899 passes while 900 does not.
Two things to be honest about. First, these exclusion rules are the published never-issued ranges; a number that passes is still almost certainly not a real, issued SSN, and the only way to know is a verification service. Second, and more important: this is exactly the kind of data you should think twice about handling at all. If you must, store it encrypted, never log it, and display it masked — the mask function above is more likely to be the useful part of this exercise than the pattern.
Common mistakes
- Putting the lookahead in the wrong place.
(?!00)must sit right before the group digits. At the start of the pattern it would check the area instead. - Thinking a match means a real SSN. The pattern only refuses ranges that are never issued. A number that passes may still not belong to anyone.
- Logging or showing the full number. Store it encrypted, keep it out of logs, and display it masked.
Try it yourself
- Write
maskLoose(value)that usesnormaliseSsnfirst, so'123456789'also masks to'***-**-6789'. - Use a negative lookahead to refuse a password that starts with
password:/^(?!password)/i. - Refuse an SSN whose nine digits are all the same, like
111-11-1111. (Hint: a separate check withnew Set.)