Emmanuel Akinfulubi

JavaScriptRegular expressions

Validate a US ZIP code in JavaScript

Beginner · 3 min read

A US ZIP code is the postal code on every American address: five digits like 90210, sometimes followed by a dash and four more, like 12345-6789. That longer form is called ZIP+4. Any checkout or shipping form that sends things to the United States checks this field.

The pattern for it is one of the shortest you will write. The real lesson of this exercise is about types: why a ZIP code must stay a string, even though it is made of digits. You need to know /.../.test(), ^ and $. Quantifiers, optional groups and named groups are explained as we go.

Counting digits with {5}

\d means "one digit". A number in curly brackets after it says how many: \d{5} is exactly five digits.

JavaScript

console.log(/^\d{5}$/.test('12345'));  // true
console.log(/^\d{5}$/.test('1234'));   // false
console.log(/^\d{5}$/.test('123456')); // false

The ^ and $ anchors make sure there is nothing else before or after.

Optional parts with ?

A ? after something makes it optional. After a group in brackets, the whole group becomes optional:

JavaScript

console.log(/^colou?r$/.test('color'));  // true
console.log(/^colou?r$/.test('colour')); // true

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

12 Validate a US zip code

easy

Check a US zip code: five digits, optionally followed by a dash and four more.

Stuck? Three hints, smallest first
  1. 1. /^\d{5}(-\d{4})?$/ is the whole pattern.
  2. 2. A zip code is not a number. 07030 loses its leading zero if you store it as one.
  3. 3. The ? makes the whole group optional, so both forms match.

Step 1: the full pattern

Five digits, then an optional group of "a dash and four digits":

Step 1

const ZIP = /^\d{5}(-\d{4})?$/;
console.log(ZIP.test('12345'));      // true
console.log(ZIP.test('12345-6789')); // true
console.log(ZIP.test('12345-678'));  // false
console.log(ZIP.test('12345 6789')); // false
console.log(ZIP.test('12345-'));     // false

A dash with no digits after it doesn't match the group, so 12345- is refused. A space instead of the dash is refused too.

Step 2: refuse values that aren't strings

A test call quietly turns its input into a string first. That means a number can sneak through:

JavaScript

console.log(/^\d{5}(-\d{4})?$/.test(12345)); // true

Adding a typeof check makes the function refuse anything that isn't a string:

Step 2

const ZIP = /^\d{5}(-\d{4})?$/;
const isZip = (value) => typeof value === 'string' && ZIP.test(value);
console.log(isZip('12345')); // true
console.log(isZip(12345));   // false

Why bother? Because of Step 3.

Step 3: why a ZIP code is not a number

Some ZIP codes start with 0, like 07030 in New Jersey. Watch what happens if that is turned into a number:

JavaScript

console.log(Number('07030'));         // 7030
console.log(String(Number('07030'))); // '7030'

The leading zero is gone, and '7030' is only four digits, so it is no longer a valid ZIP code. Numbers don't remember leading zeros.

A ZIP code is an identifier, a label, not an amount. You never add two ZIP codes together. The same is true for phone numbers and account numbers. Keep them as text in your code and in your database.

Step 4: read the parts

Sometimes you need the five-digit base and the four-digit extension separately. Named groups, written (?<name>...), label each part. (?:...) is a group that bundles the dash and extension without capturing them as a separate part:

Step 4

const ZIP_PARTS = /^(?<base>\d{5})(?:-(?<plus4>\d{4}))?$/;
const zipParts = (value) => ZIP_PARTS.exec(value)?.groups ?? null;
console.log(zipParts('12345-6789').base);  // '12345'
console.log(zipParts('12345-6789').plus4); // '6789'
console.log(zipParts('12345').plus4);      // undefined
console.log(zipParts('abc'));              // null

exec returns null when there is no match. ?.groups reads the groups only if there was a match, and ?? null turns a missing result into a clear null.

The full solution

The panel checks a list of ZIP codes, shows the leading zero vanishing when a ZIP code is stored as a number, and splits a ZIP+4 into its parts. Press Run to see each one.

The answer

const ZIP = /^\d{5}(-\d{4})?$/;
const isZip = (value) => typeof value === 'string' && ZIP.test(value);

// The ZIP+4 parts, when they are there.
const ZIP_PARTS = /^(?<base>\d{5})(?:-(?<plus4>\d{4}))?$/;
const zipParts = (value) => ZIP_PARTS.exec(value)?.groups ?? null;

const cases = ['12345', '07030', '12345-6789', '1234', '123456', '12345-678',
  '12345 6789', 'ABCDE', '', '12345-'];

for (const z of cases) console.log(JSON.stringify(z).padEnd(14), isZip(z));
console.log('--- why a zip code is text, not a number ---');
console.log("Number('07030')     =", Number('07030'), '<- the leading zero is gone');
console.log("String(Number(...)) =", String(Number('07030')), 'which is not a zip code:', isZip(String(Number('07030'))));
console.log('parts of 12345-6789:', zipParts('12345-6789'));
console.log('parts of 12345     :', zipParts('12345'));

Output


      
17 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 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test('five digits pass', isZip('12345'), true);
test('a leading zero is fine, because it is text', isZip('07030'), true);
test('the ZIP+4 form passes', isZip('12345-6789'), true);
test('four digits are too few', isZip('1234'), false);
test('six are too many', isZip('123456'), false);
test('a short extension is refused', isZip('12345-678'), false);
test('a space instead of a dash is refused', isZip('12345 6789'), false);
test('a trailing dash is refused', isZip('12345-'), false);
test('letters are refused', isZip('ABCDE'), false);
test('an empty string is refused', isZip(''), false);
test('a number is refused, since the type is wrong', isZip(12345), false);
test('storing it as a number destroys a leading zero', Number('07030'), 7030);
test('and the result is no longer a zip code', isZip(String(Number('07030'))), false);
test('the base is captured', zipParts('12345-6789').base, '12345');
test('and the extension', zipParts('12345-6789').plus4, '6789');
test('the extension is undefined when absent', zipParts('12345').plus4, undefined);
test('an invalid code parses to null', zipParts('abc'), null);

The pattern is trivial; the lesson is the type. A zip code is an identifier, not a quantity, and the assertions show Number('07030') becoming 7030 — no longer a valid code. The same applies to phone numbers, account numbers and Nigerian NIN or BVN digits. If you never do arithmetic on it, keep it as text, in the database as well as in the code.

Worth saying what this does not check: 00000 and 99999 both match and neither is a real zip code. Confirming an address exists needs a postal address dataset, not a regex.

Common mistakes

  • Storing ZIP codes as numbers. 07030 becomes 7030 and stops being a ZIP code. Keep them as strings.
  • Forgetting the anchors. Without ^ and $, '123456' passes, because it contains five digits in a row.
  • Treating a match as a real address. 00000 has the right shape but isn't a real ZIP code. A pattern checks the format only.

Try it yourself

  1. Accept a space as well as a dash before the four extra digits. (Hint: [- ].)
  2. Write formatZip(digits) that turns '123456789' into '12345-6789'.
  3. Trim the input before checking, so ' 12345 ' passes.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.