PatternRegex
Validate a UK postcode
Validate the common shape of a UK postcode — outward code, optional space, inward code — case-insensitively.
Last updated
Matches
- SW1A 1AA
- M1 1AE
- EC1A 1BB
Doesn’t match
- 12345
- SW1A 1AA
- not a postcode
Why it’s written this way
UK postcodes split into an outward code and an inward code. [A-Z]{1,2}\d[A-Z\d]? covers the outward part — one or two letters, a digit, then an optional letter or digit — which spans formats from 'M1' to 'SW1A'. The inward part, \d[A-Z]{2}, is always a digit followed by exactly two letters.
\s? makes the space between the two halves optional, since forms and copy-pasted addresses are inconsistent about including it, and the 'i' flag means the pattern doesn't care whether letters arrive as 'sw1a' or 'SW1A'.
Edge cases to know
- →A handful of real postcodes (parts of London's 'W1' series, plus some Girobank and overseas-territory codes) don't fit this general shape — the full Royal Mail specification needs a longer, more irregular pattern.
- →It accepts some letter-and-digit combinations that aren't currently allocated to any real postcode district — matching the shape isn't the same as the postcode existing.
- →Two consecutive spaces, or none where one belongs, both need normalizing first — \s? only tolerates zero or one space, not several.