How to validate UK postcodes in your application — regex patterns, edge cases, normalisation, and API-based validation.
This regex handles all standard UK postcode formats:
/^[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}$/i
It accepts postcodes with or without a space, in upper or lower case, and covers all UK postcode area formats.
function isValidUKPostcode(postcode) {
const regex = /^[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}$/i;
return regex.test(postcode.trim());
}
isValidUKPostcode('NR21 8AB'); // true
isValidUKPostcode('SW1A 1AA'); // true
isValidUKPostcode('invalid'); // false
isValidUKPostcode('NR218AB'); // true (no space)
import re
def is_valid_uk_postcode(postcode):
pattern = re.compile(r'^[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}$', re.IGNORECASE)
return bool(pattern.match(postcode.strip()))
is_valid_uk_postcode('NR21 8AB') # True
is_valid_uk_postcode('ZZ99 9ZZ') # False
function is_valid_uk_postcode(string $postcode): bool {
$pattern = '/^[A-Z]{1,2}[0-9][0-9A-Z]?\s?[0-9][A-Z]{2}$/i';
return (bool) preg_match($pattern, trim($postcode));
}
is_valid_uk_postcode('NR21 8AB'); // true
is_valid_uk_postcode('not valid'); // false
Always normalise a postcode before validating — strip whitespace, uppercase, and ensure correct spacing:
function normalisePostcode(raw) {
const p = raw.toUpperCase().replace(/\s+/g, '').trim();
return p.slice(0, -3) + ' ' + p.slice(-3);
}
// Then validate the normalised version
const postcode = normalisePostcode(userInput);
if (isValidUKPostcode(postcode)) {
// safe to use
}
| Input | Issue | Normalised |
|---|---|---|
nr21 8ab | Lowercase | NR21 8AB |
NR218AB | No space | NR21 8AB |
NR21 8AB | Leading/trailing spaces | NR21 8AB |
NR21 8AB | Double space | NR21 8AB |
BT1 1AA | Northern Ireland (BT prefix) | BT1 1AA ✓ |
For production applications, validate postcodes against a live dataset rather than just regex. The Job Bookers Routing API returns a 400 invalid_postcode error for malformed postcodes and a 404 not_found error for postcodes that don't exist in the dataset — giving you both format and existence validation in one call.
GET /v1/geocode?postcode=ZZ99+9ZZ { "error": { "code": "invalid_postcode", "message": "Not a valid UK postcode." } }
The Job Bookers Routing API validates UK postcodes and returns coordinates, drive times and street names. From £19/month.
View pricingYour bill is the same every month regardless of how you use your allocation. No overage charges, ever.
More from Job Bookers Routing API