form.validate-input
Check a text, email or number input: required, length, pattern and min/max, with GOV.UK messages.
1.0.0 · published 2026-10-10 by charlie · Anterra
Pinned by 49 tests, run in TypeScript, Python and Rust.
What it does
`validateInput(value, rules)` checks one input the way the GOV.UK Design System asks a service to, and gives the message to show. The rules are the browser's constraint attributes as data (`required`, `minlength`, `maxlength`, `pattern`, `min`, `max`, and the input's type), so the component that renders the input (`react.form.validated-input`) and the API that receives the form check exactly the same thing: TypeScript in the browser, Python or Rust on the server.
validateInput("17", { label: "Age", kind: "integer", required: true, min: "18", max: "120" });
// { valid: false, value: null, code: "too-small", message: "Age must be between 18 and 120" }
validateInput(" Ada ", { label: "Full name", kind: "text", required: true });
// { valid: true, value: "Ada", code: null, message: null }
For example
validateInput( Ada Lovelace , label Full name, kind text, required true)→ valid true, value Ada Lovelace, code —, message — a name, trimmed of spacesvalidateInput(, label Full name, kind text, required true)→ valid false, value —, code required, message Enter full name empty and required: Enter, with the label loweredvalidateInput( , label Full name, kind text, required true)→ valid false, value —, code required, message Enter full name only whitespace counts as empty
The function
The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.
export function validateInput(value: string, rules: InputRules): InputCheck
| value | string | what was typed, untrimmed; leading and trailing ASCII whitespace is ignored |
| rules | InputRules | what the input requires; the same rules the component puts on the input as attributes |
| returns | InputCheck | valid with the trimmed value, or the first rule broken and its message |
The types it declares, generated into your project
export type InputKind = "text" | "email" | "number" | "integer";
/** What an input requires of its value: the browser's constraint attributes, as data. */
export interface InputRules {
/** what the input is, as it starts a sentence: "Full name", "Number of children" */
readonly label: string;
/** text, email, number (a decimal such as -12.5) or integer */
readonly kind: InputKind;
/** an empty value is an error */
readonly required: boolean;
/** the fewest characters (Unicode code points) allowed */
readonly minLength: number | null;
/** the most characters allowed */
readonly maxLength: number | null;
/** a regular expression the whole value must match (text.pattern-match's subset) */
readonly pattern: string | null;
/** the message when the pattern does not match, such as "Enter a UK mobile number, like 07700 900 982" */
readonly patternMessage: string | null;
/** the smallest number allowed, as a decimal string ("0", "-2.5"); number and integer only */
readonly min: string | null;
/** the largest number allowed, as a decimal string */
readonly max: string | null;
}
/** The verdict on one input, shaped for its error message. */
export interface InputCheck {
readonly valid: boolean;
/** the trimmed value, when valid ("" when empty and not required) */
readonly value: string | null;
/** which rule failed: required, too-long, too-short, email, number, integer, pattern, too-small or too-large */
readonly code: string | null;
/** the error message to show, when not valid */
readonly message: string | null;
}
Your code names it in one line, in the file that uses it
import { validateInput } from "#fune/form.validate-input@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { matchesPattern } from "./text_pattern_match.ts"; ← from text.pattern-match ^1.0.0 · built alongside by fune
import { isEmail } from "./validation_email.ts"; ← from validation.email ^1.0.0 · built alongside by fune
import type { InputCheck, InputRules } from "./form_validate_input_types.ts";
// ASCII whitespace only, so all three languages trim the same characters.
function isSpace(ch: string): boolean {
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
}
function trim(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);
}
// "Full name" starts a sentence; after "Enter" it is "full name". A label that
// starts with an acronym ("UK phone number") is left as it is.
function lowerFirst(label: string): string {
const upper = (c: string | undefined) => c !== undefined && c >= "A" && c <= "Z";
if (upper(label[0]) && !upper(label[1])) return label[0].toLowerCase() + label.slice(1);
return label;
}
interface Decimal {
negative: boolean;
whole: string; // no leading zeros; "" for zero
fraction: string; // no trailing zeros
}
function isDigits(s: string): boolean {
if (s === "") return false;
for (const ch of s) if (ch < "0" || ch > "9") return false;
return true;
}
// -12, 12.5, .5 and 0.50: ASCII digits, one optional point, an optional
// leading minus. No exponent, no grouping, no plus: what a person types.
function parseDecimal(text: string, integer: boolean): Decimal | null {
let s = text;
let negative = false;
if (s.startsWith("-")) {
negative = true;
s = s.slice(1);
}
const point = s.indexOf(".");
let whole = s;
let fraction = "";
if (point >= 0) {
if (integer) return null;
whole = s.slice(0, point);
fraction = s.slice(point + 1);
if (!isDigits(fraction)) return null;
if (whole !== "" && !isDigits(whole)) return null;
} else if (!isDigits(whole)) {
return null;
}
whole = whole.replace(/^0+/, "");
fraction = fraction.replace(/0+$/, "");
if (whole === "" && fraction === "") negative = false; // -0 is 0
return { negative, whole, fraction };
}
function compareMagnitude(a: Decimal, b: Decimal): number {
if (a.whole.length !== b.whole.length) return a.whole.length < b.whole.length ? -1 : 1;
if (a.whole !== b.whole) return a.whole < b.whole ? -1 : 1;
const width = Math.max(a.fraction.length, b.fraction.length);
const fa = a.fraction.padEnd(width, "0");
const fb = b.fraction.padEnd(width, "0");
if (fa !== fb) return fa < fb ? -1 : 1;
return 0;
}
function compareDecimal(a: Decimal, b: Decimal): number {
if (a.negative !== b.negative) return a.negative ? -1 : 1;
const m = compareMagnitude(a, b);
return a.negative ? -m : m;
}
function bound(name: string, text: string | null | undefined): Decimal | null {
if (text == null) return null;
const d = parseDecimal(text, false);
if (d === null) throw new Error(`rules.${name} must be a decimal number, such as "0" or "-2.5" (got "${text}")`);
return d;
}
function fail(code: string, message: string): InputCheck {
return { valid: false, value: null, code, message };
}
/**
* One input checked as a GOV.UK form checks it: empty first, then length,
* then the format its kind needs, then the pattern, then the range, each
* failure with the message to show. The rules are the caller's, so a bad one
* throws whatever was typed.
*/
export function validateInput(value: string, rules: InputRules): InputCheck {
const label = trim(rules.label);
if (label === "") throw new Error("an input needs a label, such as \"Full name\", to write its error messages");
const numeric = rules.kind === "number" || rules.kind === "integer";
if (rules.kind !== "text" && rules.kind !== "email" && !numeric) throw new Error(`unknown input kind "${rules.kind}"`);
const { minLength, maxLength } = rules;
if (minLength != null && minLength < 0) throw new Error("rules.minLength must not be negative");
if (maxLength != null && maxLength < 0) throw new Error("rules.maxLength must not be negative");
if (minLength != null && maxLength != null && minLength > maxLength) {
throw new Error("rules.minLength must not be more than rules.maxLength");
}
if (!numeric && rules.min != null) throw new Error("rules.min only applies to number and integer inputs");
if (!numeric && rules.max != null) throw new Error("rules.max only applies to number and integer inputs");
const min = bound("min", rules.min);
const max = bound("max", rules.max);
if (min !== null && max !== null && compareDecimal(min, max) > 0) {
throw new Error("rules.min must not be more than rules.max");
}
// A bad pattern fails here, on every call, not only when someone types.
if (rules.pattern != null) matchesPattern(rules.pattern, "");
const text = trim(value);
if (text === "") {
return rules.required ? fail("required", `Enter ${lowerFirst(label)}`) : { valid: true, value: "", code: null, message: null };
}
const length = Array.from(text).length;
if (maxLength != null && length > maxLength) return fail("too-long", `${label} must be ${maxLength} characters or less`);
if (minLength != null && length < minLength) return fail("too-short", `${label} must be ${minLength} characters or more`);
let number: Decimal | null = null;
if (rules.kind === "email" && !isEmail(text)) {
return fail("email", "Enter an email address in the correct format, like name@example.com");
}
if (rules.kind === "number") {
number = parseDecimal(text, false);
if (number === null) return fail("number", `${label} must be a number`);
}
if (rules.kind === "integer") {
number = parseDecimal(text, true);
if (number === null) return fail("integer", `${label} must be a whole number`);
}
if (rules.pattern != null && !matchesPattern(rules.pattern, text)) {
return fail("pattern", rules.patternMessage ?? `Enter ${lowerFirst(label)} in the correct format`);
}
if (number !== null) {
const low = min !== null && compareDecimal(number, min) < 0;
const high = max !== null && compareDecimal(number, max) > 0;
if (low || high) {
const code = low ? "too-small" : "too-large";
if (min !== null && max !== null) return fail(code, `${label} must be between ${rules.min} and ${rules.max}`);
if (low) return fail(code, `${label} must be ${rules.min} or more`);
return fail(code, `${label} must be ${rules.max} or less`);
}
}
return { valid: true, value: text, code: null, message: null };
}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.validate-input
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./form.validate-input-1.0.0-typescript.fune, or fetch it from a terminal with fune pull form.validate-input@1.0.0:typescript.
The whole function, every language, is one file too: form.validate-input-1.0.0.fune, 46,929 bytes, sha256 25917279c20761f4e80f9d2baece597a3a2cbce54132582e4259e65868ad1b4f. 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.validate-input
after — your function gets the result and the arguments, and returns the final result.
// fune: after form.validate-input
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.validate-input
// fune: replace validation.email in form.validate-input
step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show form.validate-input --steps.
// fune: step form.validate-input 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.
| Case | Arguments | Expected | |
|---|---|---|---|
| a name, trimmed of spaces | Ada Lovelace , label Full name, kind text, required true | → | valid true, value Ada Lovelace, code —, message — |
| empty and required: Enter, with the label lowered | , label Full name, kind text, required true | → | valid false, value —, code required, message Enter full name |
| only whitespace counts as empty | , label Full name, kind text, required true | → | valid false, value —, code required, message Enter full name |
| an acronym label keeps its capitals | , label UK phone number, kind text, required true | → | valid false, value —, code required, message Enter UK phone number |
| empty and optional is valid, as the empty string | , label Middle name, kind text, required false | → | valid true, value , code —, message — |
| empty and optional skips every other rule | , label Age, kind integer, required false, min 18 | → | valid true, value , code —, message — |
| too long: GOV.UK's 'characters or less' | abcdefghijk, label Reference, kind text, required true, max length 10 | → | valid false, value —, code too-long, message Reference must be 10 characters or less |
| exactly the maximum length is fine | abcdefghij, label Reference, kind text, required true, max length 10 | → | valid true, value abcdefghij, code —, message — |
| too short | ab, label Reference, kind text, required true, min length 3 | → | valid false, value —, code too-short, message Reference must be 3 characters or more |
| length counts code points: an emoji is one | 😀😀😀, label Reaction, kind text, required true, max length 3 | → | valid true, value 😀😀😀, code —, message — |
Show the other 39 tests
| Case | Arguments | Expected | |
|---|---|---|---|
| length is checked on the trimmed value | abc , label Code, kind text, required true, min length 3, max length 3 | → | valid true, value abc, code —, message — |
| a valid email address | name@example.com, label Email address, kind email, required true | → | valid true, value name@example.com, code —, message — |
| an email address without a domain | name@, label Email address, kind email, required true | → | valid false, value —, code email, message Enter an email address in the correct format, like name@example.com |
| an email address with a trailing newline is trimmed, then valid | name@example.com , label Email address, kind email, required true | → | valid true, value name@example.com, code —, message — |
| length is checked before the email format | a@b.co, label Email address, kind email, required true, min length 8 | → | valid false, value —, code too-short, message Email address must be 8 characters or more |
| a decimal number | -12.50, label Temperature, kind number, required true | → | valid true, value -12.50, code —, message — |
| a number with no whole part | .5, label Ratio, kind number, required true | → | valid true, value .5, code —, message — |
| not a number | twelve, label Temperature, kind number, required true | → | valid false, value —, code number, message Temperature must be a number |
| grouping commas are not a number | 1,000, label Amount, kind number, required true | → | valid false, value —, code number, message Amount must be a number |
| a plus sign is not accepted | +5, label Amount, kind number, required true | → | valid false, value —, code number, message Amount must be a number |
| a trailing point is not a number | 5., label Amount, kind number, required true | → | valid false, value —, code number, message Amount must be a number |
| Arabic-Indic digits are not a number | ١٢, label Amount, kind number, required true | → | valid false, value —, code number, message Amount must be a number |
| a whole number | 3, label Number of children, kind integer, required true | → | valid true, value 3, code —, message — |
| a decimal is not a whole number | 2.5, label Number of children, kind integer, required true | → | valid false, value —, code integer, message Number of children must be a whole number |
| 2.0 is not a whole number as typed | 2.0, label Number of children, kind integer, required true | → | valid false, value —, code integer, message Number of children must be a whole number |
| below the minimum, with only a minimum | 17, label Age, kind integer, required true, min 18 | → | valid false, value —, code too-small, message Age must be 18 or more |
| above the maximum, with only a maximum | 121, label Age, kind integer, required true, max 120 | → | valid false, value —, code too-large, message Age must be 120 or less |
| outside both bounds says between | 0, label Rating, kind integer, required true, min 1, max 5 | → | valid false, value —, code too-small, message Rating must be between 1 and 5 |
| above both bounds says between, code too-large | 6, label Rating, kind integer, required true, min 1, max 5 | → | valid false, value —, code too-large, message Rating must be between 1 and 5 |
| the bounds are inclusive | 5, label Rating, kind integer, required true, min 1, max 5 | → | valid true, value 5, code —, message — |
| decimals compare exactly, no floating point: 0.3 is not below 0.30 | 0.3, label Dose, kind number, required true, min 0.30, max 0.5 | → | valid true, value 0.3, code —, message — |
| a long decimal just over the maximum | 10.000000000000000001, label Score, kind number, required true, max 10 | → | valid false, value —, code too-large, message Score must be 10 or less |
| negative numbers compare the right way round | -3, label Offset, kind number, required true, min -2.5 | → | valid false, value —, code too-small, message Offset must be -2.5 or more |
| -0 is zero, not below it | -0, label Change, kind number, required true, min 0 | → | valid true, value -0, code —, message — |
| leading zeros do not change the number | 007, label Count, kind integer, required true, max 7 | → | valid true, value 007, code —, message — |
| a pattern that matches | SW1A 1AA, label Postcode, kind text, required true, pattern [A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2} | → | valid true, value SW1A 1AA, code —, message — |
| a pattern that does not match: the default message | 12345, label Postcode, kind text, required true, pattern [A-Z]{1,2}[0-9][A-Z0-9]? ?[0-9][A-Z]{2} | → | valid false, value —, code pattern, message Enter postcode in the correct format |
| a pattern that does not match: the caller's message | 0770090098, label Mobile number, kind text, required true, pattern 07[0-9]{3} ?[0-9]{3} ?[0-9]{3}, pattern message Enter a UK mobile number, like 07700 900 982 | → | valid false, value —, code pattern, message Enter a UK mobile number, like 07700 900 982 |
| the pattern must match the whole value | AB12x, label Code, kind text, required true, pattern [A-Z]{2}[0-9]{2} | → | valid false, value —, code pattern, message Enter code in the correct format |
| the number format is checked before the pattern | abc, label PIN, kind integer, required true, pattern [0-9]{4} | → | valid false, value —, code integer, message PIN must be a whole number |
| the pattern is checked before the range | 12, label PIN, kind integer, required true, pattern [0-9]{4}, min 1000 | → | valid false, value —, code pattern, message Enter PIN in the correct format |
| an empty label is an error | x, label , kind text, required true | → | error: an input needs a label |
| min on a text input is an error | x, label Name, kind text, required true, min 1 | → | error: rules.min only applies to number and integer inputs |
| max on an email input is an error | a@b.co, label Email, kind email, required true, max 1 | → | error: rules.max only applies to number and integer inputs |
| a minimum that is not a decimal is an error | 5, label Age, kind integer, required true, min ten | → | error: rules.min must be a decimal number |
| min above max is an error | 5, label Age, kind integer, required true, min 10, max 2 | → | error: rules.min must not be more than rules.max |
| minLength above maxLength is an error | abc, label Code, kind text, required true, min length 5, max length 2 | → | error: rules.minLength must not be more than rules.maxLength |
| a negative maxLength is an error | abc, label Code, kind text, required true, max length -1 | → | error: rules.maxLength must not be negative |
| a pattern outside the portable subset is an error even when the value is empty | , label Password, kind text, required false, pattern (?=.*[0-9]).{8,} | → | error: unsupported pattern |
Verification
Verified by the operator, not the sandbox 49 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
## Order of the checks
The first rule broken is the one reported, in this order:
1. **required**: the value, trimmed of ASCII whitespace, is empty. Empty and not required is valid (`value: ""`) and nothing else is checked. 2. **too-long**, then **too-short**: `maxLength` and `minLength`. 3. the kind's format: **email** (validation.email's `isEmail`), **number** or **integer**. 4. **pattern**: text.pattern-match on the trimmed value. 5. **too-small** / **too-large**: `min` and `max`, number and integer only.
So a too-long email address is told it is too long rather than malformed, and a PIN typed as letters is told it must be a whole number before the pattern is tried.
## Messages
GOV.UK's wording, with the label as it starts a sentence ("Full name"):
| code | message | |------|---------| | required | Enter full name (the label's first letter lowered, unless it starts with an acronym: "Enter UK phone number") | | too-long | Full name must be 35 characters or less | | too-short | Reference must be 3 characters or more | | email | Enter an email address in the correct format, like name@example.com | | number | Temperature must be a number | | integer | Number of children must be a whole number | | pattern | `patternMessage` when given, else "Enter postcode in the correct format". Give one: only the caller knows what the format is | | too-small / too-large | Rating must be between 1 and 5; Age must be 18 or more; Age must be 120 or less (`code` says which side) |
`min` and `max` are shown exactly as given, so give them as they should read.
## Decisions
- **Numbers are decimal strings, compared exactly.** `min`, `max` and the value are compared digit by digit, never as floats, so `0.3` is not below `0.30` and `10.000000000000000001` is above `10` in every language. The value accepted is what a person types: ASCII digits, one optional point, an optional leading minus (`-12.5`, `.5`, `007`). No `+`, no grouping commas, no exponent, no trailing point; those are "must be a number". A money amount, with its currency and grouping, is form.money-input's job. - **integer** refuses any point, even `2.0`: the person typed a decimal. - **The value is trimmed** of ASCII whitespace (GOV.UK asks services to accept leading and trailing spaces), and the trimmed value is returned to store. Unicode spaces are not trimmed, so the three languages agree. - **Length counts Unicode code points**, so `"😀"` is one character in every language. The browser's `maxlength` counts UTF-16 code units, where an emoji is two: for text outside the Basic Multilingual Plane the browser stops typing earlier than this check would refuse, never later. - **The pattern applies to every kind**, after the kind's own format check. The browser ignores `pattern` on `type="number"`, which is one more reason react.form.validated-input renders numbers as text with an input mode. - **Bad rules throw** whatever was typed: an empty label, an unknown kind, a negative or crossed length, `min`/`max` on a text or email input, a bound that is not a decimal, `min` above `max`, or a pattern text.pattern-match refuses (its "unsupported pattern" message). They are programming errors, so the first test catches them, not the first user.
## 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,217 |
| README.md | 4,383 |
| impl/python.py | 6,703 |
| impl/rust.rs | 9,398 |
| impl/typescript.ts | 6,550 |
| vectors.json | 11,453 |