Functional Weave
Code in Python

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

  • validate_input( Ada Lovelace , label Full name, kind text, required true) → valid true, value Ada Lovelace, code —, message — a name, trimmed of spaces
  • validate_input(, label Full name, kind text, required true) → valid false, value —, code required, message Enter full name empty and required: Enter, with the label lowered
  • validate_input( , 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.

def validate_input(value: str, rules: InputRules) -> InputCheck
valuestringwhat was typed, untrimmed; leading and trailing ASCII whitespace is ignored
rulesInputRuleswhat the input requires; the same rules the component puts on the input as attributes
returnsInputCheckvalid with the trimmed value, or the first rule broken and its message

The types it declares, generated into your project

InputKind = Literal["text", "email", "number", "integer"]

@dataclass(frozen=True)
class InputRules:
    """What an input requires of its value: the browser's constraint attributes, as data."""

    #: what the input is, as it starts a sentence: "Full name", "Number of children"
    label: str
    #: text, email, number (a decimal such as -12.5) or integer
    kind: InputKind
    #: an empty value is an error
    required: bool
    #: the fewest characters (Unicode code points) allowed
    min_length: Optional[int]
    #: the most characters allowed
    max_length: Optional[int]
    #: a regular expression the whole value must match (text.pattern-match's subset)
    pattern: Optional[str]
    #: the message when the pattern does not match, such as "Enter a UK mobile number, like 07700 900 982"
    pattern_message: Optional[str]
    #: the smallest number allowed, as a decimal string ("0", "-2.5"); number and integer only
    min: Optional[str]
    #: the largest number allowed, as a decimal string
    max: Optional[str]

@dataclass(frozen=True)
class InputCheck:
    """The verdict on one input, shaped for its error message."""

    valid: bool
    #: the trimmed value, when valid ("" when empty and not required)
    value: Optional[str]
    #: which rule failed: required, too-long, too-short, email, number, integer, pattern, too-small or too-large
    code: Optional[str]
    #: the error message to show, when not valid
    message: Optional[str]

Your code names it in one line, in the file that uses it

from fune.form.validate_input import validate_input  # form.validate-input@^1
impl/python.py · 164 lines · open · raw

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, Tuple

from .form_validate_input_types import InputCheck, InputRules
from .text_pattern_match import matches_pattern  ← from text.pattern-match ^1.0.0 · built alongside by fune
from .validation_email import is_email  ← from validation.email ^1.0.0 · built alongside by fune

# ASCII whitespace only, so all three languages trim the same characters
# (str.strip() with no argument would also take Unicode spaces).
_SPACE = " \t\n\r\f\v"

# A decimal is (negative, whole digits without leading zeros, fraction digits
# without trailing zeros); zero is (False, "", "").
Decimal = Tuple[bool, str, str]


def _lower_first(label: str) -> str:
    # "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.
    def upper(i: int) -> bool:
        return i < len(label) and "A" <= label[i] <= "Z"

    if upper(0) and not upper(1):
        return chr(ord(label[0]) + 32) + label[1:]
    return label


def _is_digits(s: str) -> bool:
    # ASCII digits only: str.isdigit() accepts "٣".
    return s != "" and all("0" <= ch <= "9" for ch in s)


def _parse_decimal(text: str, integer: bool) -> Optional[Decimal]:
    # -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.
    s = text
    negative = False
    if s.startswith("-"):
        negative = True
        s = s[1:]
    point = s.find(".")
    whole = s
    fraction = ""
    if point >= 0:
        if integer:
            return None
        whole = s[:point]
        fraction = s[point + 1:]
        if not _is_digits(fraction):
            return None
        if whole != "" and not _is_digits(whole):
            return None
    elif not _is_digits(whole):
        return None
    whole = whole.lstrip("0")
    fraction = fraction.rstrip("0")
    if whole == "" and fraction == "":
        negative = False  # -0 is 0
    return (negative, whole, fraction)


def _compare_magnitude(a: Decimal, b: Decimal) -> int:
    if len(a[1]) != len(b[1]):
        return -1 if len(a[1]) < len(b[1]) else 1
    if a[1] != b[1]:
        return -1 if a[1] < b[1] else 1
    width = max(len(a[2]), len(b[2]))
    fa = a[2].ljust(width, "0")
    fb = b[2].ljust(width, "0")
    if fa != fb:
        return -1 if fa < fb else 1
    return 0


def _compare_decimal(a: Decimal, b: Decimal) -> int:
    if a[0] != b[0]:
        return -1 if a[0] else 1
    m = _compare_magnitude(a, b)
    return -m if a[0] else m


def _bound(name: str, text: Optional[str]) -> Optional[Decimal]:
    if text is None:
        return None
    d = _parse_decimal(text, False)
    if d is None:
        raise ValueError('rules.%s must be a decimal number, such as "0" or "-2.5" (got "%s")' % (name, text))
    return d


def _fail(code: str, message: str) -> InputCheck:
    return InputCheck(valid=False, value=None, code=code, message=message)


def validate_input(value: str, rules: InputRules) -> InputCheck:
    """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 raises whatever was typed."""
    label = rules.label.strip(_SPACE)
    if label == "":
        raise ValueError('an input needs a label, such as "Full name", to write its error messages')
    kind = rules.kind
    numeric = kind in ("number", "integer")
    if kind not in ("text", "email") and not numeric:
        raise ValueError('unknown input kind "%s"' % kind)
    min_length, max_length = rules.min_length, rules.max_length
    if min_length is not None and min_length < 0:
        raise ValueError("rules.minLength must not be negative")
    if max_length is not None and max_length < 0:
        raise ValueError("rules.maxLength must not be negative")
    if min_length is not None and max_length is not None and min_length > max_length:
        raise ValueError("rules.minLength must not be more than rules.maxLength")
    if not numeric and rules.min is not None:
        raise ValueError("rules.min only applies to number and integer inputs")
    if not numeric and rules.max is not None:
        raise ValueError("rules.max only applies to number and integer inputs")
    low_bound = _bound("min", rules.min)
    high_bound = _bound("max", rules.max)
    if low_bound is not None and high_bound is not None and _compare_decimal(low_bound, high_bound) > 0:
        raise ValueError("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 is not None:
        matches_pattern(rules.pattern, "")

    text = value.strip(_SPACE)
    if text == "":
        if rules.required:
            return _fail("required", "Enter %s" % _lower_first(label))
        return InputCheck(valid=True, value="", code=None, message=None)
    length = len(text)  # code points, as in the other two languages
    if max_length is not None and length > max_length:
        return _fail("too-long", "%s must be %d characters or less" % (label, max_length))
    if min_length is not None and length < min_length:
        return _fail("too-short", "%s must be %d characters or more" % (label, min_length))

    number: Optional[Decimal] = None
    if kind == "email" and not is_email(text):
        return _fail("email", "Enter an email address in the correct format, like name@example.com")
    if kind == "number":
        number = _parse_decimal(text, False)
        if number is None:
            return _fail("number", "%s must be a number" % label)
    if kind == "integer":
        number = _parse_decimal(text, True)
        if number is None:
            return _fail("integer", "%s must be a whole number" % label)

    if rules.pattern is not None and not matches_pattern(rules.pattern, text):
        message = rules.pattern_message
        if message is None:
            message = "Enter %s in the correct format" % _lower_first(label)
        return _fail("pattern", message)

    if number is not None:
        low = low_bound is not None and _compare_decimal(number, low_bound) < 0
        high = high_bound is not None and _compare_decimal(number, high_bound) > 0
        if low or high:
            code = "too-small" if low else "too-large"
            if low_bound is not None and high_bound is not None:
                return _fail(code, "%s must be between %s and %s" % (label, rules.min, rules.max))
            if low:
                return _fail(code, "%s must be %s or more" % (label, rules.min))
            return _fail(code, "%s must be %s or less" % (label, rules.max))
    return InputCheck(valid=True, value=text, code=None, message=None)

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.validate-input
Download for Python form.validate-input-1.0.0-python.fune · 30,245 bytes sha256 ac09f1d1ea73e4feb8d4e4e0218744fbf9b4bb21363b8cf7b9f2d13fa7afcce6

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./form.validate-input-1.0.0-python.fune, or fetch it from a terminal with fune pull form.validate-input@1.0.0:python.

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.

CaseArgumentsExpected
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
CaseArgumentsExpected
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

PathBytes
NOTICE1,217
README.md4,383
impl/python.py6,703
impl/rust.rs9,398
impl/typescript.ts6,550
vectors.json11,453