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.
- validateAddress (address: Address) -> AddressCheck
- addressFormat (country: string) -> AddressFormat
The types it declares, generated into your project
/** A postal address as an address form collects it. */
export interface Address {
/** the building and street */
readonly line1: string;
/** more of the street address (optional) */
readonly line2: string | null;
/** the town or city */
readonly town: string;
/** county, state, province or region (optional) */
readonly region: string | null;
/** the postcode, ZIP code or postal code */
readonly postcode: string | null;
/** ISO 3166-1 alpha-2 code: GB for the UK form */
readonly country: string;
}
/** One field in error. */
export interface AddressError {
/** line1, line2, town, region, postcode or country: the form field to mark */
readonly field: string;
/** what is wrong, to show above the field */
readonly message: string;
}
/** The verdict on a whole address. */
export interface AddressCheck {
readonly valid: boolean;
/** the normalised address, when valid */
readonly address: Address | null;
/** one per field in error, in form order; empty when valid */
readonly errors: readonly AddressError[];
}
/** How a country's address form asks for and checks its fields. */
export interface AddressFormat {
/** the ISO code, upper case */
readonly country: string;
/** the country's English short name */
readonly name: string;
/** the UK pattern applies: GB and the Crown Dependencies (GG, JE, IM) */
readonly uk: boolean;
/** Postcode, ZIP code, Postal code, PIN code or Eircode */
readonly postcodeLabel: string;
/** every address in the country has one */
readonly postcodeRequired: boolean;
/** a valid example, for the hint */
readonly postcodeExample: string | null;
/** County, State, Province or Region */
readonly regionLabel: string;
}
Once installed, your code imports each one from the group's module.
validateAddress 25 tests
export function validateAddress(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
validateAddress(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 normalisedvalidateAddress(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 casevalidateAddress(line1 , line2 —, town , region —, postcode , country GB)→ valid false, address —, errors ×3 UK: nothing typed - an error for each required field, in form order
import { validateAddress } from "#fune/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.
import { isUkFamily, lookupCountry, trimAscii, upperAscii } from "./form_address_address_format.ts"; ← addressFormat, another function of this group · built into the same file, even by a slim install
import { matchesPattern } from "./text_pattern_match.ts"; ← from text.pattern-match ^1.0.0 · built alongside by fune
import { validateUkPostcode } from "./validation_uk_postcode.ts"; ← from validation.uk-postcode ^2.0.0 · built alongside by fune
import type { Address, AddressCheck, AddressError } from "./form_address_types.ts";
const MAX_LENGTH = 100;
// Unicode code points, so an accented town counts as the letters it has.
function length(value: string): number {
return [...value].length;
}
// "Enter postcode", but "Enter ZIP code" and "Enter Eircode": only the two
// ordinary labels are common nouns.
function inSentence(label: string): string {
return label === "Postcode" || label === "Postal code" ? label[0].toLowerCase() + label.slice(1) : label;
}
// Without a known format: 1 to 12 letters, digits, spaces and hyphens.
function plausiblePostcode(value: string): boolean {
if (value.length < 1 || value.length > 12) return false;
for (const ch of value) {
const ok = (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9") || ch === " " || ch === "-";
if (!ok) return false;
}
return true;
}
/**
* A postal address checked field by field, the GOV.UK Design System's address
* pattern for the UK and the same rules, with the country's own postcode
* format and labels, everywhere else. Never throws: an unknown country is the
* country field's error.
*/
export function validateAddress(address: Address): AddressCheck {
const errors: AddressError[] = [];
const row = lookupCountry(address.country);
const regionLabel = row?.regionLabel ?? "Region";
const postcodeLabel = row?.postcodeLabel ?? "Postal code";
const line1 = trimAscii(address.line1);
if (line1 === "") errors.push({ field: "line1", message: "Enter address line 1, typically the building and street" });
else if (length(line1) > MAX_LENGTH) errors.push({ field: "line1", message: `Address line 1 must be ${MAX_LENGTH} characters or less` });
const line2 = trimAscii(address.line2 ?? "");
if (length(line2) > MAX_LENGTH) errors.push({ field: "line2", message: `Address line 2 must be ${MAX_LENGTH} characters or less` });
const town = trimAscii(address.town);
if (town === "") errors.push({ field: "town", message: "Enter town or city" });
else if (length(town) > MAX_LENGTH) errors.push({ field: "town", message: `Town or city must be ${MAX_LENGTH} characters or less` });
const region = trimAscii(address.region ?? "");
if (length(region) > MAX_LENGTH) errors.push({ field: "region", message: `${regionLabel} must be ${MAX_LENGTH} characters or less` });
const typed = trimAscii(address.postcode ?? "");
let postcode: string | null = null;
if (typed === "") {
if (row?.postcodeRequired) errors.push({ field: "postcode", message: `Enter ${inSentence(postcodeLabel)}` });
} else if (row !== null && isUkFamily(row.code)) {
const uk = validateUkPostcode(typed);
if (uk.valid) postcode = uk.normalised;
else errors.push({ field: "postcode", message: `Enter a real ${inSentence(postcodeLabel)}` });
} else {
const upper = upperAscii(typed);
const pattern = row?.postcodePattern ?? null;
const ok = pattern !== null ? matchesPattern(pattern, upper) : plausiblePostcode(upper);
if (ok) postcode = upper;
else errors.push({ field: "postcode", message: `Enter a real ${inSentence(postcodeLabel)}` });
}
if (row === null) errors.push({ field: "country", message: "Select a country" });
if (errors.length > 0 || row === null) return { valid: false, address: null, errors };
return {
valid: true,
address: { line1, line2: line2 === "" ? null : line2, town, region: region === "" ? null : region, postcode, country: row.code },
errors: [],
};
}addressFormat throws on bad input 12 tests
export function addressFormat(country: string): 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
addressFormat(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 patternaddressFormat(us)→ country US, name United States, uk false, postcode label ZIP code, postcode required true, postcode example 20500, region label State lower case is acceptedaddressFormat( de )→ country DE, name Germany, uk false, postcode label Postcode, postcode required true, postcode example 10115, region label State surrounding spaces are trimmed
import { addressFormat } from "#fune/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.
import { COUNTRIES } from "./form_address_data.ts"; ← this capability’s own data, compiled from data/countries.json into the same file by fune build
import type { AddressFormat } from "./form_address_types.ts";
type Country = (typeof COUNTRIES)[number];
// The UK and the Crown Dependencies share Royal Mail's postcode format.
const UK_FAMILY = ["GB", "GG", "JE", "IM"];
function isSpace(ch: string): boolean {
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
}
/** Leading and trailing ASCII whitespace removed, the same in every language. */
export function trimAscii(value: string): string {
let start = 0;
let end = value.length;
while (start < end && isSpace(value[start])) start++;
while (end > start && isSpace(value[end - 1])) end--;
return value.slice(start, end);
}
/** ASCII letters upper-cased; everything else as it is. */
export function upperAscii(value: string): string {
return value.replace(/[a-z]/g, (c) => c.toUpperCase());
}
/** Whether a country code (already upper case) uses the UK postcode format. */
export function isUkFamily(code: string): boolean {
return UK_FAMILY.includes(code);
}
/** The country's row, by its code as typed (trimmed, any case), or null. */
export function lookupCountry(country: string): Country | null {
const code = upperAscii(trimAscii(country));
return COUNTRIES.find((row) => row.code === code) ?? null;
}
/**
* How an address form for a country labels and checks its fields: the UK
* pattern for GB and the Crown Dependencies, the country's own name for its
* postcode (ZIP code, PIN code, Eircode) and region (State, Province) elsewhere.
*/
export function addressFormat(country: string): AddressFormat {
const row = lookupCountry(country);
if (row === null) throw new Error(`unknown country "${country}": give an ISO 3166-1 alpha-2 code, such as GB, US or DE`);
return {
country: row.code,
name: row.name,
uk: isUkFamily(row.code),
postcodeLabel: row.postcodeLabel,
postcodeRequired: row.postcodeRequired,
postcodeExample: row.postcodeExample,
regionLabel: row.regionLabel,
};
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 2 dependencies, pins them in fune.lock, downloads only the TypeScript 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 TypeScript implementation. Install it without the registry with fune add ./form.address-1.0.0-typescript.fune, or fetch it from a terminal with fune pull form.address@1.0.0:typescript.
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 |