UK postcode implementation
UK Postcode Regex and Validation Examples
A postcode regular expression is useful for catching malformed input, but the safest implementation normalises human input first and treats syntax, current existence and address verification as separate checks.
By PostcodeLab · Published · Updated
Download the UK postcode validation test suite
The downloadable fixtures now have a dedicated canonical resource page. Open the UK Postcode Validation Test Suite for all 40 cases, stable and versioned JSON/CSV files, JSON Schema, integrity manifest, exact field contracts and automation examples.
This regex guide remains focused on implementation and normalisation. The suite is a separate QA resource so teams can cite, pin and verify it without treating an article about regular expressions as the dataset itself.
Test your UK postcode regex against 40 cases
The Custom UK Postcode Regex Test Runner compares a pattern with seven valid shapes, seven normalisation cases, two empty inputs and twenty-four deliberately invalid values. It tests each fixture's expected_normalised value after PostcodeLab normalisation, so it measures regex compatibility rather than your own normalisation implementation.
Privacy and safety: the runner does not send or store your pattern. It runs in a same-origin Web Worker, accepts regex source rather than executable code and stops a run that exceeds 500 milliseconds. PostcodeLab contains advertising scripts, so this statement describes the runner's own behaviour rather than making a claim about every third-party script on the page.
Result limit: 40/40 means only that the pattern is compatible with PostcodeLab v1.0.1 syntax fixtures after PostcodeLab normalisation. It is not official certification, does not test your normaliser and does not prove allocation, current existence, address association or deliverability.
Normalise before applying a regex
People paste postcodes in lower case, without a space, with several spaces or surrounded by common punctuation. Rejecting those superficial differences creates avoidable errors. This site's documented contract trims the value, converts it to upper case, removes whitespace and the punctuation characters shown below, then inserts one space before the final three characters.
function normaliseUKPostcode(value) {
const compact = String(value)
.trim()
.toUpperCase()
.replace(/[.(){}\[\]\-–—]/g, '')
.replace(/\s+/g, '');
if (compact.length < 5 || compact.length > 7) return null;
return compact.slice(0, -3) + ' ' + compact.slice(-3);
}
Keep the raw value when an audit trail requires it, but compare and validate the normalised value. Do not silently remove arbitrary letters or digits because that can change the user's intended postcode. If your product chooses a narrower punctuation policy, keep that policy and its fixtures together.
Use the interactive UK postcode checker to exercise the same spacing and syntax behaviour directly in your browser.
A practical BS 7666-style pattern
The following case-insensitive JavaScript pattern applies Royal Mail's published position rules for outward-code letters and inward-code letters. It is suitable as a syntax screen after normalisation, including the special GIR 0AA form.
const UK_POSTCODE =
/^(?:GIR 0AA|(?:(?:[A-PR-UWYZ][0-9]{1,2}|[A-PR-UWYZ][A-HK-Y][0-9]{1,2}|[A-PR-UWYZ][0-9][A-HJKSTUW]|[A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2}))$/i;
function hasUKPostcodeShape(value) {
const postcode = normaliseUKPostcode(value);
return postcode !== null && UK_POSTCODE.test(postcode);
}
A regex copied from another system may implement different business rules, such as BFPO or non-geographic codes. Document which formats your product accepts and keep the test cases beside the expression.
Test every structural format
| Shape | Format example | Test purpose |
|---|---|---|
AN NAA | M1 1AA | Shortest common outward code |
ANN NAA | M60 1NW | Two-digit district |
AAN NAA | CR2 6XH | Two-letter area |
AANN NAA | DN55 1PT | Long numeric district |
ANA NAA | W1A 1HQ | Letter after the district digit |
AANA NAA | EC1A 1BB | Longest standard outward code |
Also test lower-case input, no space, leading and trailing whitespace, repeated spaces, empty input, punctuation, too few characters and too many characters. Format examples demonstrate structure only and should not be used as proof of deliverability.
Regex cannot prove a postcode exists
A successful pattern match means only that the string has an accepted shape. It cannot tell you whether the postcode is current, terminated, mistyped but plausible, associated with a particular address or deliverable by a chosen carrier.
When existence matters, compare against a maintained postcode source or lookup service. The ONS Postcode Directory and National Statistics Postcode Lookup include current and terminated postcodes and are released quarterly, while address-level decisions may require a licensed address product.
Make validation recoverable
Run the same validation on the server, but do not rely on a restrictive HTML pattern alone. GOV.UK guidance recommends accepting unambiguous formatting differences and explaining what went wrong and how the user can fix it.
- Associate the error with the postcode input and move focus to an error summary when appropriate.
- Preserve the entered value so the user can correct it.
- Offer manual address entry when lookup fails.
- Do not claim that syntax validation verifies an address or identity.
Keep regex rules and fixtures versioned together
A regex is part of a validation contract, not an isolated snippet. Record its supported formats, normalisation order and excluded cases beside the code. When those decisions change, update the pattern and its regression expectations in one reviewed change.
PostcodeLab publishes its fixture history, exact field definitions and immutable download checks on the validation test suite version page. Pin a suite version when reproducibility matters.
Official references
Related developer guides
UK Postcode Validation Test Suite
Download 40 versioned UK postcode validation test cases in JSON or CSV, with expected results, JSON Schema, SHA-256 manifest and automation examples.
Read guideUK Postcode Format and Validation Guide
Understand UK postcode structure, outward and inward codes, normalisation, syntax validation, lookup checks and practical QA test cases.
Read guidePostcode Validation vs Address Verification
Compare postcode syntax validation, postcode lookup, address verification, UPRN matching and deliverability checks when designing UK forms and tests.
Read guideUK Address Form Test Cases and QA Checklist
Use practical UK address form test cases for field variation, postcodes, lookup failure, accessibility, mobile layouts, exports and integration safety.
Read guide