form.address
Check a UK or international postal address form: required lines, lengths, country and postcode.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 37 tests, run in TypeScript, Python and Rust.validateAddress 25 · addressFormat 12
What it does
The checks behind an address form, in TypeScript, Python and Rust, so the browser and the API refuse the same addresses with the same words (`react.form.address-fields` renders the form and shows these errors).
- **`validateAddress(address)`** checks every field and returns all the errors at once, in form order (line1, line2, town, region, postcode, country), each naming the field to mark. When valid it returns the address to store: trimmed, empty optional lines as `null`, the country code upper case, and the postcode in its standard form (`sw1a2aa` is `SW1A 2AA`). It never throws: an unknown or missing country is the country field's error. - **`addressFormat(country)`** says how the form for a country asks: the label for its postcode (Postcode, ZIP code, PIN code, Eircode, Postal code) and its region (County, State, Province, Prefecture, Canton...), whether the postcode is required, an example for the hint, and whether the UK pattern applies. It throws `unknown country` for a code that is not ISO 3166-1 alpha-2.
The functions
A group: 2 functions that work together, each in its own file, each pinned by its own tests in TypeScript, Python and Rust. A project can install only the ones it calls.
- validate_address (address: Address) -> AddressCheck
- address_format (country: string) -> AddressFormat
The types it declares, generated into your project
@dataclass(frozen=True)
class Address:
"""A postal address as an address form collects it."""
#: the building and street
line1: str
#: more of the street address (optional)
line2: Optional[str]
#: the town or city
town: str
#: county, state, province or region (optional)
region: Optional[str]
#: the postcode, ZIP code or postal code
postcode: Optional[str]
#: ISO 3166-1 alpha-2 code: GB for the UK form
country: str
@dataclass(frozen=True)
class AddressError:
"""One field in error."""
#: line1, line2, town, region, postcode or country: the form field to mark
field: str
#: what is wrong, to show above the field
message: str
@dataclass(frozen=True)
class AddressCheck:
"""The verdict on a whole address."""
valid: bool
#: the normalised address, when valid
address: Optional[Address]
#: one per field in error, in form order; empty when valid
errors: List[AddressError]
@dataclass(frozen=True)
class AddressFormat:
"""How a country's address form asks for and checks its fields."""
#: the ISO code, upper case
country: str
#: the country's English short name
name: str
#: the UK pattern applies: GB and the Crown Dependencies (GG, JE, IM)
uk: bool
#: Postcode, ZIP code, Postal code, PIN code or Eircode
postcode_label: str
#: every address in the country has one
postcode_required: bool
#: a valid example, for the hint
postcode_example: Optional[str]
#: County, State, Province or Region
region_label: str
Once installed, your code imports each one from the group's module.
validate_address 25 tests
def validate_address(address: Address) -> AddressCheck
| address | Address | the form's fields as typed, untrimmed |
| returns | AddressCheck | valid with the address normalised (trimmed, postcode in its standard form), or an error per field |
For example
validate_address(line1 10 Downing Street, line2 —, town London, region —, postcode sw1a2aa, country GB)→ valid true, address …, errors UK: a postcode in lower case without its space is normalisedvalidate_address(line1 1 High Street , line2 , town Leeds , region West Yorkshire , postcode LS1 1AA, country gb )→ valid true, address …, errors UK: fields trimmed, an empty line 2 is null, country in any casevalidate_address(line1 , line2 —, town , region —, postcode , country GB)→ valid false, address —, errors ×3 UK: nothing typed - an error for each required field, in form order
from fune.form.address import validate_address # form.address@^1
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import List, Optional
from .form_address_address_format import is_uk_family, lookup_country, trim_ascii, upper_ascii ← addressFormat, another function of this group · built into the same file, even by a slim install
from .form_address_types import Address, AddressCheck, AddressError
from .text_pattern_match import matches_pattern ← from text.pattern-match ^1.0.0 · built alongside by fune
from .validation_uk_postcode import validate_uk_postcode ← from validation.uk-postcode ^2.0.0 · built alongside by fune
MAX_LENGTH = 100
def _in_sentence(label: str) -> str:
# "Enter postcode", but "Enter ZIP code" and "Enter Eircode": only the two
# ordinary labels are common nouns.
if label in ("Postcode", "Postal code"):
return label[0].lower() + label[1:]
return label
def _plausible_postcode(value: str) -> bool:
# Without a known format: 1 to 12 letters, digits, spaces and hyphens.
if not 1 <= len(value) <= 12:
return False
return all("A" <= ch <= "Z" or "0" <= ch <= "9" or ch in " -" for ch in value)
def validate_address(address: Address) -> AddressCheck:
"""A postal address checked field by field: the GOV.UK address pattern for
the UK, the country's own postcode format and labels elsewhere. Never
raises: an unknown country is the country field's error."""
errors: List[AddressError] = []
row = lookup_country(address.country)
region_label = row.region_label if row is not None else "Region"
postcode_label = row.postcode_label if row is not None else "Postal code"
line1 = trim_ascii(address.line1)
if line1 == "":
errors.append(AddressError(field="line1", message="Enter address line 1, typically the building and street"))
elif len(line1) > MAX_LENGTH:
errors.append(AddressError(field="line1", message="Address line 1 must be %d characters or less" % MAX_LENGTH))
line2 = trim_ascii(address.line2 or "")
if len(line2) > MAX_LENGTH:
errors.append(AddressError(field="line2", message="Address line 2 must be %d characters or less" % MAX_LENGTH))
town = trim_ascii(address.town)
if town == "":
errors.append(AddressError(field="town", message="Enter town or city"))
elif len(town) > MAX_LENGTH:
errors.append(AddressError(field="town", message="Town or city must be %d characters or less" % MAX_LENGTH))
region = trim_ascii(address.region or "")
if len(region) > MAX_LENGTH:
errors.append(AddressError(field="region", message="%s must be %d characters or less" % (region_label, MAX_LENGTH)))
typed = trim_ascii(address.postcode or "")
postcode: Optional[str] = None
if typed == "":
if row is not None and row.postcode_required:
errors.append(AddressError(field="postcode", message="Enter %s" % _in_sentence(postcode_label)))
elif row is not None and is_uk_family(row.code):
uk = validate_uk_postcode(typed)
if uk.valid:
postcode = uk.normalised
else:
errors.append(AddressError(field="postcode", message="Enter a real %s" % _in_sentence(postcode_label)))
else:
upper = upper_ascii(typed)
pattern = row.postcode_pattern if row is not None else None
ok = matches_pattern(pattern, upper) if pattern is not None else _plausible_postcode(upper)
if ok:
postcode = upper
else:
errors.append(AddressError(field="postcode", message="Enter a real %s" % _in_sentence(postcode_label)))
if row is None:
errors.append(AddressError(field="country", message="Select a country"))
if errors or row is None:
return AddressCheck(valid=False, address=None, errors=errors)
return AddressCheck(
valid=True,
address=Address(
line1=line1,
line2=line2 if line2 != "" else None,
town=town,
region=region if region != "" else None,
postcode=postcode,
country=row.code,
),
errors=[],
)address_format throws on bad input 12 tests
def address_format(country: str) -> AddressFormat
| country | string | ISO 3166-1 alpha-2 code, such as GB, US or DE; case does not matter |
| returns | AddressFormat | how an address form for that country labels and checks its fields |
For example
address_format(GB)→ country GB, name United Kingdom, uk true, postcode label Postcode, postcode required true, postcode example SW1A 2AA, region label County the United Kingdom: the GOV.UK patternaddress_format(us)→ country US, name United States, uk false, postcode label ZIP code, postcode required true, postcode example 20500, region label State lower case is acceptedaddress_format( de )→ country DE, name Germany, uk false, postcode label Postcode, postcode required true, postcode example 10115, region label State surrounding spaces are trimmed
from fune.form.address import address_format # form.address@^1
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
from typing import Optional
from .form_address_data import COUNTRIES ← this capability’s own data, compiled from data/countries.json into the same file by fune build
from .form_address_types import AddressFormat
# The UK and the Crown Dependencies share Royal Mail's postcode format.
UK_FAMILY = ("GB", "GG", "JE", "IM")
_SPACE = " \t\n\r\f\v"
def trim_ascii(value: str) -> str:
"""Leading and trailing ASCII whitespace removed, the same in every language."""
return value.strip(_SPACE)
def upper_ascii(value: str) -> str:
"""ASCII letters upper-cased; everything else as it is (str.upper() would
also change "ß" and other scripts)."""
return "".join(chr(ord(c) - 32) if "a" <= c <= "z" else c for c in value)
def is_uk_family(code: str) -> bool:
"""Whether a country code (already upper case) uses the UK postcode format."""
return code in UK_FAMILY
def lookup_country(country: str):
"""The country's row, by its code as typed (trimmed, any case), or None."""
code = upper_ascii(trim_ascii(country))
for row in COUNTRIES:
if row.code == code:
return row
return None
def address_format(country: str) -> AddressFormat:
"""How an address form for a country labels and checks its fields."""
row = lookup_country(country)
if row is None:
raise ValueError('unknown country "%s": give an ISO 3166-1 alpha-2 code, such as GB, US or DE' % country)
return AddressFormat(
country=row.code,
name=row.name,
uk=is_uk_family(row.code),
postcode_label=row.postcode_label,
postcode_required=row.postcode_required,
postcode_example=row.postcode_example,
region_label=row.region_label,
)Install
fune build
With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 2 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:
fune add form.address
That builds the whole group. To build only what you call, and whatever it uses inside the group:
fune add form.address --only validateAddress
The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./form.address-1.0.0-python.fune, or fetch it from a terminal with fune pull form.address@1.0.0:python.
The whole function, every language, is one file too: form.address-1.0.0.fune, 95,840 bytes, sha256 0f02ef12f4bc85a40492c323bd5fb2a0bd74d37ce42a08aa326decfcc04d4a12. It installs into a project of any language.
Customise it in your app
The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.
before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.
# fune: before form.address.validateAddress
# fune: before form.address.addressFormat
after — your function gets the result and the arguments, and returns the final result.
# fune: after form.address.validateAddress
# fune: after form.address.addressFormat
replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.
# fune: replace text.pattern-match in form.address
# fune: replace validation.uk-postcode in form.address
step — your function runs at a numbered point inside a function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show form.address --steps.
# fune: step form.address.<fn> after <n|label>
Tests
A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.
validateAddress 25 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| UK: a postcode in lower case without its space is normalised | line1 10 Downing Street, line2 —, town London, region —, postcode sw1a2aa, country GB | → | valid true, address …, errors |
| UK: fields trimmed, an empty line 2 is null, country in any case | line1 1 High Street , line2 , town Leeds , region West Yorkshire , postcode LS1 1AA, country gb | → | valid true, address …, errors |
| UK: nothing typed - an error for each required field, in form order | line1 , line2 —, town , region —, postcode , country GB | → | valid false, address —, errors ×3 |
| UK: a postcode one character short | line1 10 Downing Street, line2 —, town London, region —, postcode SW1A 2A, country GB | → | valid false, address —, errors ×1 |
| UK: a trailing newline on the postcode is trimmed | line1 10 Downing Street, line2 —, town London, region —, postcode SW1A 2AA , country GB | → | valid true, address …, errors |
| UK: a tab inside the postcode is not a space | line1 10 Downing Street, line2 —, town London, region —, postcode SW1A 2AA, country GB | → | valid false, address —, errors ×1 |
| Jersey uses the UK postcode format | line1 1 Bond Street, line2 —, town St Helier, region —, postcode je2 3ab, country JE | → | valid true, address …, errors |
| US: ZIP+4 is accepted, with the state | line1 1600 Pennsylvania Avenue NW, line2 —, town Washington, region DC, postcode 20500-0003, country US | → | valid true, address …, errors |
| US: a four-digit ZIP code | line1 1600 Pennsylvania Avenue NW, line2 —, town Washington, region —, postcode 2050, country US | → | valid false, address —, errors ×1 |
| US: the ZIP code is required, and named as a ZIP code | line1 1600 Pennsylvania Avenue NW, line2 —, town Washington, region —, postcode , country US | → | valid false, address —, errors ×1 |
Show the other 15 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| Canada: upper-cased, spacing kept as typed | line1 24 Sussex Drive, line2 —, town Ottawa, region —, postcode k1a0b1, country CA | → | valid true, address …, errors |
| Netherlands: 1012 ab becomes 1012 AB | line1 Dam 1, line2 —, town Amsterdam, region —, postcode 1012 ab, country NL | → | valid true, address …, errors |
| Ireland: the Eircode is optional | line1 1 Main Street, line2 —, town Dublin, region —, postcode —, country IE | → | valid true, address …, errors |
| Ireland: a short Eircode keeps its proper name in the message | line1 1 Main Street, line2 —, town Dublin, region —, postcode D02 X28, country IE | → | valid false, address —, errors ×1 |
| India: a PIN code has six digits | line1 1 Rajpath, line2 —, town New Delhi, region —, postcode 1100, country IN | → | valid false, address —, errors ×1 |
| Germany: Arabic-Indic digits are not a postcode | line1 Unter den Linden 1, line2 —, town Berlin, region —, postcode ١٠١١٥, country DE | → | valid false, address —, errors ×1 |
| Hong Kong has no postcodes: none is fine | line1 1 Queen's Road Central, line2 —, town Hong Kong, region —, postcode —, country HK | → | valid true, address …, errors |
| no known format: letters, digits, spaces and hyphens, up to 12 | line1 1 Queen's Road Central, line2 —, town Hong Kong, region —, postcode 999077, country HK | → | valid true, address …, errors |
| no known format: a # is not in a postal code | line1 1 Queen's Road Central, line2 —, town Hong Kong, region —, postcode AB#12, country HK | → | valid false, address —, errors ×1 |
| an unknown country is the country field's error, not an exception | line1 1 Main Street, line2 —, town Springfield, region —, postcode 12345, country XX | → | valid false, address —, errors ×1 |
| no country chosen | line1 1 Main Street, line2 —, town Springfield, region —, postcode , country | → | valid false, address —, errors ×1 |
| 100 accented letters is 100 characters, not 200 bytes | line1 éééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééééé, line2 —, town Paris, region —, postcode 75008, country FR | → | valid true, address …, errors |
| 101 characters is too long for line 1 | line1 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx, line2 —, town Paris, region —, postcode 75008, country FR | → | valid false, address —, errors ×1 |
| a long region is named by the country's label | line1 1 Main Street, line2 —, town Austin, region TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT, postcode 73301, country US | → | valid false, address —, errors ×1 |
| errors keep form order: line 2 before town | line1 1 Main Street, line2 yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy, town , region —, postcode 75008, country FR | → | valid false, address —, errors ×2 |
addressFormat 12 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| the United Kingdom: the GOV.UK pattern | GB | → | country GB, name United Kingdom, uk true, postcode label Postcode, postcode required true, postcode example SW1A 2AA, region label County |
| lower case is accepted | us | → | country US, name United States, uk false, postcode label ZIP code, postcode required true, postcode example 20500, region label State |
| surrounding spaces are trimmed | de | → | country DE, name Germany, uk false, postcode label Postcode, postcode required true, postcode example 10115, region label State |
| Guernsey is in the UK family, with parishes | GG | → | country GG, name Guernsey, uk true, postcode label Postcode, postcode required true, postcode example GY1 1AA, region label Parish |
| Ireland: an optional Eircode | IE | → | country IE, name Ireland, uk false, postcode label Eircode, postcode required false, postcode example D02 X285, region label County |
| India: a PIN code and states | IN | → | country IN, name India, uk false, postcode label PIN code, postcode required true, postcode example 110001, region label State |
| Canada: provinces | CA | → | country CA, name Canada, uk false, postcode label Postal code, postcode required true, postcode example K1A 0B1, region label Province |
| Hong Kong: no postcode format | HK | → | country HK, name Hong Kong, uk false, postcode label Postal code, postcode required false, postcode example —, region label District |
| the United Arab Emirates: emirates | AE | → | country AE, name United Arab Emirates, uk false, postcode label Postal code, postcode required false, postcode example —, region label Emirate |
| an unknown code | XX | → | error: unknown country |
Show the other 2 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| an empty code | → | error: unknown country | |
| an alpha-3 code is not alpha-2 | GBR | → | error: unknown country |
Verification
Verified by the operator, not the sandbox 37 test vectors declared; none run by the registry.
Verified locally by the registry's operator, not by the sandbox. This version was published with FUNE_VERIFY_MODE=inline-dev (the operator's import of the first-party registry, or a development server): the server validated the package - its manifest, signatures, imports, safety lint and test rules - but the registry did not run its test vectors in its sandbox. The operator runs them with `fune verify --all` before importing.
Signed by the registry with key fw-9dc887227da47575 (ed25519), over its integrity and this report's digest. The full report · JSON
More from the author
## The rules
| Field | Rule | Message | |-------|------|---------| | line1 | required, at most 100 characters | Enter address line 1, typically the building and street | | line2 | optional, at most 100 | Address line 2 must be 100 characters or less | | town | required, at most 100 | Enter town or city | | region | optional, at most 100 | `<regionLabel>` must be 100 characters or less | | postcode | required where `postcodeRequired`; the country's format | Enter postcode / Enter a real ZIP code | | country | one of the 249 ISO 3166-1 alpha-2 codes | Select a country |
The wording is the GOV.UK Design System's address pattern. Lengths count Unicode code points, so "Zürich" is 6. Whitespace trimmed is ASCII only, the same in every language.
**UK postcodes** (GB and the Crown Dependencies GG, JE and IM, which use Royal Mail's format) are checked and normalised by `validation.uk-postcode`, so the letter rules it knows apply, and GIR 0AA is accepted.
**Other countries**: the postcode's ASCII letters are upper-cased (spacing is kept as typed), then matched against the country's pattern in `data/countries.json` with `text.pattern-match`, the same subset of regular expressions a browser's `pattern` attribute takes, so the component can put the pattern on the input too. 45 countries have a pattern (US, CA, the EU states, AU, NZ, IN, JP, CN, BR, MX, ZA, SG, KR...). A country without one accepts 1 to 12 letters, digits, spaces and hyphens, and does not require a postcode. Ireland's Eircode is optional, as most Irish forms make it.
## What it does not do
A well-formed address is not a real one: this checks shape, not existence. Only an address lookup (Royal Mail PAF in the UK, USPS, Eircode's finder) can say an address exists; it is network work, and a gap in the `forms` suite. Address lines are not split or reordered for a country's postal format, and a region is free text, not checked against a list of states.
Country names are the English short names from ISO 3166-1 (`Türkiye`, `Côte d'Ivoire`, `Korea` as `South Korea`).
## Notices
Error message wording follows the GOV.UK Design System. Portions derived from GOV.UK Frontend (https://github.com/alphagov/govuk-frontend), Copyright (c) 2017 Crown Copyright (Government Digital Service), under the MIT License; the full notice is in NOTICE.
Files
| Path | Bytes |
|---|---|
| NOTICE | 1,210 |
| README.md | 3,394 |
| data/countries.json | 43,981 |
| impl/python/address_format.py | 1,635 |
| impl/python/validate_address.py | 3,820 |
| impl/rust/address_format.rs | 2,369 |
| impl/rust/validate_address.rs | 5,995 |
| impl/typescript/address_format.ts | 2,053 |
| impl/typescript/validate_address.ts | 3,719 |
| vectors.json | 12,471 |