belfastbuild-backend / backend /app /postcodes.py
pritamdeka
commit
21f359b
Raw
History Blame Contribute Delete
1.01 kB
"""Northern Ireland postcode validation.
The spec requires the API edge to reject non-NI postcodes (e.g. English
``SW1A 1AA``) with a 422 response before any LLM call. The official NI
postcode format is ``BT`` followed by a digit, an optional letter, an optional
digit, then an optional space and a 3-character alphanumeric outward code.
The regex below covers the published BT1–BT92 range used by Royal Mail.
"""
from __future__ import annotations
import re
# NI postcode formats documented by Royal Mail / nidirect:
# BT1 5GS, BT9 7AG, BT15 4ET, BT38 8QB
# Single regex (case-insensitive) covering the BT-prefixed outward code.
_NI_POSTCODE_RE = re.compile(
r"^BT(?:\d{1,2}|9[0-57-9])(?:\s?[A-Z0-9]{3})$",
re.IGNORECASE,
)
def is_ni_postcode(value: str) -> bool:
"""Return True if *value* matches the Northern Ireland postcode format."""
if not isinstance(value, str):
return False
candidate = value.strip().upper()
return bool(_NI_POSTCODE_RE.match(candidate))