Validate a UK postcode in JavaScript
Advanced · 3 min read
UK postcodes look like M1 1AE, DN55 1PT or EC1A 1BB. Every online shop that delivers in the UK asks for one, and many forms use it to look up the rest of the address. Before the lookup, a quick pattern check catches typos, like a missing letter or a stray digit.
UK postcodes come in more shapes than most postal codes, so this exercise is a good workout for character classes, optional parts and counted repeats. You will also tidy the input into the standard form: capitals, with one space before the last three characters. You need to know /.../.test(), ^, $ and \d. Everything else is explained as we go.
The two halves of a postcode
A postcode has two halves, separated by a space:
DN55 1PT
outward: DN55 the area and district (2 to 4 characters)
inward: 1PT always a digit and two letters
The inward half never changes shape. All the variety is in the outward half, which has six documented forms:
M1 1AE letter, digit
B33 8TH letter, digit, digit
CR2 6XH letter, letter, digit
DN55 1PT letter, letter, digit, digit
W1A 0AX letter, digit, letter
EC1A 1BB letter, letter, digit, letter
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
13 Validate a UK postcode
hardCheck a UK postcode. The format is more varied than most: one or two letters, then digits, then optionally a letter, then a space, then a digit and two letters.
Stuck? Three hints, smallest first
- 1. The outward code is 2 to 4 characters; the inward code is always a digit and two letters.
- 2. Real examples that must all pass:
M1 1AE,B33 8TH,CR2 6XH,DN55 1PT,EC1A 1BB,W1A 0AX. - 3. The space is optional in stored data, so allow it to be missing and normalise afterwards.
Step 1: the inward half
A digit followed by exactly two capital letters. {2} means "exactly two of the thing before":
const INWARD = /^\d[A-Z]{2}$/;
console.log(INWARD.test('1AE')); // true
console.log(INWARD.test('1A')); // false
console.log(INWARD.test('1AEE')); // false
Step 2: the outward half
Look at the six forms again. Each one is: one or two letters, then a digit, then maybe one more character, which is either a digit or a letter.
[A-Z]{1,2}is one or two letters ({1,2}means "between one and two").\dis the required digit.[A-Z\d]?is an optional letter-or-digit. A class can mix ranges and\d.
const OUTWARD = /^[A-Z]{1,2}\d[A-Z\d]?$/;
for (const o of ['M1', 'B33', 'CR2', 'DN55', 'W1A', 'EC1A']) {
console.log(o, OUTWARD.test(o)); // every line ends in true
}
console.log(OUTWARD.test('MMM1')); // false: three letters
Step 3: join them
Put the halves together with \s? between them, an optional whitespace character. Stored data often has the space removed, so it's kinder to allow both. The i flag lets lower-case input through:
const UK_POSTCODE = /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i;
const isUkPostcode = (value) => typeof value === 'string' && UK_POSTCODE.test(value.trim());
console.log(isUkPostcode('EC1A 1BB')); // true
console.log(isUkPostcode('SW1A2AA')); // true: no space
console.log(isUkPostcode('m1 1ae')); // true: lower case
console.log(isUkPostcode(' M1 1AE ')); // true: trimmed first
console.log(isUkPostcode('12345')); // false
console.log(isUkPostcode('M1')); // false: outward half only
Step 4: tidy it into the standard form
Postcodes are normally written in capitals with one space before the last three characters. Since the inward half is always three characters, you don't need to work out where the outward half ends. Remove every space, then put one back three from the end:
const UK_POSTCODE = /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i;
const isUkPostcode = (value) => typeof value === 'string' && UK_POSTCODE.test(value.trim());
function normaliseUkPostcode(value) {
if (!isUkPostcode(value)) return null;
const bare = value.trim().toUpperCase().replace(/\s+/g, '');
return `${bare.slice(0, -3)} ${bare.slice(-3)}`;
}
console.log(normaliseUkPostcode('m11ae')); // 'M1 1AE'
console.log(normaliseUkPostcode('ec1a 1bb')); // 'EC1A 1BB'
console.log(normaliseUkPostcode('XYZ')); // null
slice(0, -3) is everything except the last three characters, and slice(-3) is the last three. Tidying input like this means two people typing the same postcode differently still end up with the same text.
Step 5: know the limits
There is a real postcode this pattern refuses:
const UK_POSTCODE = /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i;
console.log(UK_POSTCODE.test('GIR 0AA')); // false
GIR 0AA is a special postcode that doesn't follow the general rule. The official rules have a few named exceptions like this, and a pattern that handles every case is much longer. For anything important, use a postcode lookup service; the pattern only catches typos.
The full solution
The panel checks all six documented forms, a list of bad inputs, and tidies each good one. Press Run and check every tidied postcode has exactly one space.
/* Outward: 1-2 letters, a digit, then optionally another digit or a letter.
Inward: always a digit and two letters.
The space is optional, because stored data often has it stripped. */
const UK_POSTCODE = /^[A-Z]{1,2}\d[A-Z\d]?\s?\d[A-Z]{2}$/i;
const isUkPostcode = (value) => typeof value === 'string' && UK_POSTCODE.test(value.trim());
// Postcodes are conventionally stored and shown upper case with one space
// before the final three characters.
function normaliseUkPostcode(value) {
if (!isUkPostcode(value)) return null;
const bare = value.trim().toUpperCase().replace(/\s+/g, '');
return `${bare.slice(0, -3)} ${bare.slice(-3)}`;
}
// The six documented format variants, all of which must pass.
const real = ['M1 1AE', 'B33 8TH', 'CR2 6XH', 'DN55 1PT', 'EC1A 1BB', 'W1A 0AX'];
const bad = ['12345', 'XYZ', 'M1', '1AE', 'MMM1 1AE', 'M1 1A', 'M1 1AEE', ''];
for (const p of real) console.log('real ', p.padEnd(10), isUkPostcode(p), '-> normalised', JSON.stringify(normaliseUkPostcode(p)));
for (const p of bad) console.log('bad ', JSON.stringify(p).padEnd(10), isUkPostcode(p));
console.log('no space :', isUkPostcode('SW1A2AA'), '-> normalised', JSON.stringify(normaliseUkPostcode('SW1A2AA')));
console.log('lower case:', isUkPostcode('m1 1ae'), '-> normalised', JSON.stringify(normaliseUkPostcode('m1 1ae')));
Output
22 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 22 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('all six documented variants pass', real.every(isUkPostcode), true);
test('a one-letter area with one digit', isUkPostcode('M1 1AE'), true);
test('a two-letter area with two digits', isUkPostcode('DN55 1PT'), true);
test('a district with a trailing letter', isUkPostcode('EC1A 1BB'), true);
test('the London W1A form', isUkPostcode('W1A 0AX'), true);
test('the space may be missing', isUkPostcode('SW1A2AA'), true);
test('lower case is accepted', isUkPostcode('m1 1ae'), true);
test('surrounding spaces are tolerated', isUkPostcode(' M1 1AE '), true);
test('digits alone are refused', isUkPostcode('12345'), false);
test('letters alone are refused', isUkPostcode('XYZ'), false);
test('the outward code alone is refused', isUkPostcode('M1'), false);
test('the inward code alone is refused', isUkPostcode('1AE'), false);
test('three leading letters are refused', isUkPostcode('MMM1 1AE'), false);
test('a short inward code is refused', isUkPostcode('M1 1A'), false);
test('a long inward code is refused', isUkPostcode('M1 1AEE'), false);
test('an empty string is refused', isUkPostcode(''), false);
test('normalising upper-cases and spaces it', normaliseUkPostcode('m11ae'), 'M1 1AE');
test('an already-tidy code is unchanged', normaliseUkPostcode('EC1A 1BB'), 'EC1A 1BB');
test('every normalised code has exactly one space', real.every((p) => normaliseUkPostcode(p).split(' ').length === 2), true);
test('and three characters after it', real.every((p) => normaliseUkPostcode(p).split(' ')[1].length === 3), true);
test('an invalid code normalises to null', normaliseUkPostcode('XYZ'), null);
test('but GIR 0AA, a real special case, is refused by this pattern', isUkPostcode('GIR 0AA'), false);
The inward code is the stable half: always a digit and two letters. All the variation is in the outward code, which is why the pattern is [A-Z]{1,2}d[A-Zd]? — one or two letters, a digit, then optionally either another digit or a letter. The six examples in the assertions are the documented format variants, and a pattern that fails any of them is wrong.
Making the space optional and normalising afterwards is the practical choice: stored data has often had it stripped, and users type it inconsistently. Normalise on the way in so comparisons work.
The last assertion is deliberate. GIR 0AA is a genuine postcode (Girobank, Bootle) and this pattern rejects it, because it does not fit the general rule. That is the honest state of postcode validation — the official rules include named exceptions, and a pattern that handles every real case is considerably longer than this one. For anything that matters, use a postcode lookup service; a regex catches typos and nothing more.
Common mistakes
- Requiring the space. People and databases often leave it out. Allow it to be missing, then add it back when tidying.
- Writing a fixed length.
[A-Z]{2}\d{2}only matches one of the six forms. The outward half is two to four characters. - Treating a match as a real address. A made-up postcode with the right shape still passes. Only a lookup can confirm a postcode exists.
Try it yourself
- Write
outwardOf(postcode)that returns'EC1A'for'EC1A 1BB'. (Hint: tidy it, then split on the space.) - Add a special case so
GIR 0AApasses too. - Change the check to refuse the no-space form, then decide which version is friendlier for a form.