Functional Weave
Code in Python

form.file-check

Check files chosen in an upload field: accept types, size, empty files and how many, with GOV.UK messages.

1.0.0 · published 2026-10-10 by charlie · Anterra

Pinned by 52 tests, run in TypeScript, Python and Rust.validateFiles 22 · acceptsFile 14 · formatFileSize 16

What it does

The checks behind a file upload field, so the browser and the server refuse the same files with the same words. `react.form.file-upload` calls it as files are chosen; the API that receives the upload (or that signs the upload URL with `storage.signed-url`) calls it again, in TypeScript, Python or Rust, on the names, sizes and types it is told about.

validateFiles(
  [{ name: "setup.exe", size: 100, mimeType: "application/x-msdownload" }],
  { required: true, accept: ".pdf", maxBytes: 2 * 1024 * 1024, multiple: false, maxFiles: null },
);
// { valid: false, message: "The selected file must be a PDF",
//   errors: [{ index: 0, name: "setup.exe", code: "type", message: "The selected file must be a PDF" }] }

The functions

A group: 3 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.

  1. validate_files (files: FileInfo[], rules: FileRules) -> FileCheck
  2. accepts_file (accept: string, file: FileInfo) -> bool
  3. format_file_size (bytes: int) -> string

The types it declares, generated into your project

@dataclass(frozen=True)
class FileInfo:
    """One chosen file, as the browser describes it."""

    #: the file's name, such as report.pdf
    name: str
    #: bytes
    size: int
    #: the MIME type the browser guessed (File.type); may be ""
    mime_type: str

@dataclass(frozen=True)
class FileRules:
    """What a file upload field requires."""

    #: at least one file must be chosen
    required: bool
    #: an accept attribute; null or empty accepts any file
    accept: Optional[str]
    #: the largest size allowed for each file
    max_bytes: Optional[int]
    #: more than one file may be chosen
    multiple: bool
    #: the most files allowed when multiple
    max_files: Optional[int]

@dataclass(frozen=True)
class FileError:
    """One error: the field's (index -1) or one file's."""

    #: the file's position in files, or -1 for the field as a whole
    index: int
    #: the file's name, null for the field
    name: Optional[str]
    #: required, one-file, too-many, type, too-large or empty
    code: str
    #: what is wrong, to show
    message: str

@dataclass(frozen=True)
class FileCheck:
    """The verdict on a file upload field."""

    valid: bool
    #: the first error's message, for the error summary
    message: Optional[str]
    #: every error, the field's first, then each file's in order; empty when valid
    errors: List[FileError]

Once installed, your code imports each one from the group's module.

validate_files throws on bad input 22 tests

def validate_files(files: Sequence[FileInfo], rules: FileRules) -> FileCheck
filesFileInfo[]what was chosen: each file's name, size in bytes and MIME type, as the browser's File gives them
rulesFileRulesaccept, size limit and how many files
returnsFileCheckvalid, or every error: the field's, and each file's

For example

  • validate_files(, required true, accept .pdf, max bytes 2,097,152, multiple false, max files —) → valid false, message Select a file, errors ×1 nothing chosen in a required field: Select a file
  • validate_files(, required false, accept .pdf, max bytes 2,097,152, multiple false, max files —) → valid true, message —, errors nothing chosen in an optional field is valid
  • validate_files(files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files —) → valid true, message —, errors one PDF within the size limit
from fune.form.file_check import validate_files  # form.file-check@^1
impl/python/validate_files.py · 55 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 List, Sequence

from .form_file_check_accepts_file import accept_tokens, describe_accept, matches_accept  ← acceptsFile, another function of this group · built into the same file, even by a slim install
from .form_file_check_format_file_size import format_file_size  ← formatFileSize, another function of this group · built into the same file, even by a slim install
from .form_file_check_types import FileCheck, FileError, FileInfo, FileRules


def _whole(value: object) -> bool:
    return isinstance(value, int) and not isinstance(value, bool)


def validate_files(files: Sequence[FileInfo], rules: FileRules) -> FileCheck:
    """The files chosen in an upload field, checked the way the GOV.UK Design
    System's file upload asks: the field's own errors first, then each
    file's, at most one each (type, then empty, then too large)."""
    if rules.max_bytes is not None and (not _whole(rules.max_bytes) or rules.max_bytes < 0):
        raise ValueError("rules.maxBytes must be a size of 0 or more, got %r" % (rules.max_bytes,))
    if rules.max_files is not None:
        if not rules.multiple:
            raise ValueError("rules.maxFiles only applies when rules.multiple is true")
        if not _whole(rules.max_files) or rules.max_files < 1:
            raise ValueError("rules.maxFiles must be at least 1, got %r" % (rules.max_files,))
    tokens = accept_tokens(rules.accept if rules.accept is not None else "")
    for file in files:
        if not _whole(file.size) or file.size < 0:
            raise ValueError(
                'file size must be a whole number of bytes, 0 or more, got %r for "%s"' % (file.size, file.name)
            )

    errors: List[FileError] = []
    if len(files) == 0:
        if rules.required:
            message = "Select at least one file" if rules.multiple else "Select a file"
            errors.append(FileError(index=-1, name=None, code="required", message=message))
    elif not rules.multiple and len(files) > 1:
        errors.append(FileError(index=-1, name=None, code="one-file", message="Select only one file"))
    elif rules.max_files is not None and len(files) > rules.max_files:
        noun = "file" if rules.max_files == 1 else "files"
        errors.append(
            FileError(index=-1, name=None, code="too-many", message="You can only select up to %d %s" % (rules.max_files, noun))
        )

    for index, file in enumerate(files):
        subject = "The selected file" if len(files) == 1 else file.name
        if not matches_accept(tokens, file):
            code, message = "type", "%s must be %s" % (subject, describe_accept(tokens))
        elif file.size == 0:
            code, message = "empty", "%s is empty" % subject
        elif rules.max_bytes is not None and file.size > rules.max_bytes:
            code, message = "too-large", "%s must be %s or smaller" % (subject, format_file_size(rules.max_bytes))
        else:
            continue
        errors.append(FileError(index=index, name=file.name, code=code, message=message))

    return FileCheck(valid=not errors, message=errors[0].message if errors else None, errors=errors)

accepts_file throws on bad input 14 tests

def accepts_file(accept: str, file: FileInfo) -> bool
acceptstringan accept attribute: comma-separated extensions (.pdf), MIME types (application/pdf) and wildcards (image/*); empty accepts anything
fileFileInfothe file to test
returnsboolwhether the browser's file chooser would offer it

For example

  • accepts_file(.pdf, name report.PDF, size 1, mime type application/pdf) → true by extension, ignoring case
  • accepts_file(.pdf, name report.pdf.exe, size 1, mime type ) → false the extension must end the name
  • accepts_file(image/*, name photo.heic, size 1, mime type image/heic) → true a type/* wildcard matches the MIME type
from fune.form.file_check import accepts_file  # form.file-check@^1
impl/python/accepts_file.py · 93 lines · open · raw
from typing import List, Sequence

from .form_file_check_types import FileInfo

# ASCII whitespace only, so all three languages trim the same characters.
_SPACE = " \t\n\r\f\v"
_MIME_PUNCTUATION = "!#$&^_.+-"


def _lower(value: str) -> str:
    return "".join(chr(ord(c) + 32) if "A" <= c <= "Z" else c for c in value)


def _upper(value: str) -> str:
    return "".join(chr(ord(c) - 32) if "a" <= c <= "z" else c for c in value)


def _is_mime_name(value: str) -> bool:
    # RFC 6838's restricted-name characters.
    return value != "" and all(
        "a" <= c <= "z" or "A" <= c <= "Z" or "0" <= c <= "9" or c in _MIME_PUNCTUATION for c in value
    )


def accept_tokens(accept: str) -> List[str]:
    """The accept attribute's tokens, trimmed and lower-cased, empty ones
    dropped. Anything that is not an extension, a MIME type or a type/*
    wildcard raises."""
    tokens: List[str] = []
    for raw in accept.split(","):
        token = _lower(raw.strip(_SPACE))
        if token == "":
            continue
        ok = False
        if token.startswith("."):
            ext = token[1:]
            ok = ext != "" and "/" not in ext and not any(c in _SPACE for c in ext)
        else:
            slash = token.find("/")
            if slash > 0:
                kind, subtype = token[:slash], token[slash + 1 :]
                ok = _is_mime_name(kind) and (subtype == "*" or _is_mime_name(subtype))
        if not ok:
            raise ValueError(
                'accept token "%s" is not an extension (.pdf), a MIME type (application/pdf) or a wildcard (image/*)'
                % raw.strip(_SPACE)
            )
        tokens.append(token)
    return tokens


def describe_accept(tokens: Sequence[str]) -> str:
    """What the accepted types are called in an error message: "a PDF",
    "an image", "a PDF, JPG or PNG"."""
    words: List[str] = []
    for token in tokens:
        if token.startswith("."):
            word = _upper(token[1:])
        elif token.endswith("/*"):
            word = token[:-2]
        else:
            word = _upper(token[token.find("/") + 1 :])
        if word not in words:
            words.append(word)
    listed = words[0] if len(words) == 1 else "%s or %s" % (", ".join(words[:-1]), words[-1])
    first = words[0][0]
    # A lower-case word is said as a word; an initialism letter by letter.
    an = first in "aeiou" if "a" <= first <= "z" else first in "AEFHILMNORSX8"
    return "%s %s" % ("an" if an else "a", listed)


def matches_accept(tokens: Sequence[str], file: FileInfo) -> bool:
    if not tokens:
        return True
    name = _lower(file.name)
    kind = _lower(file.mime_type)
    for token in tokens:
        if token.startswith("."):
            if name.endswith(token):
                return True
        elif token.endswith("/*"):
            if kind.startswith(token[:-1]):
                return True
        elif kind == token:
            return True
    return False


def accepts_file(accept: str, file: FileInfo) -> bool:
    """Whether a browser's file chooser would offer this file for an accept
    attribute: by extension, exact MIME type or type/* wildcard, ignoring
    case. An empty accept takes anything."""
    return matches_accept(accept_tokens(accept), file)

format_file_size throws on bad input 16 tests

def format_file_size(bytes: int) -> str
bytesinta size in bytes, 0 or more
returnsstring"512 bytes", "1KB", "1.5MB", "2GB": units of 1024, one decimal place when not whole

For example

  • format_file_size(0) → 0 bytes nothing
  • format_file_size(1) → 1 byte one byte, singular
  • format_file_size(1,023) → 1023 bytes just under a kilobyte
from fune.form.file_check import format_file_size  # form.file-check@^1
impl/python/format_file_size.py · 28 lines · open · raw
UNITS = ("KB", "MB", "GB", "TB")


def format_file_size(bytes: int) -> str:
    """A size for people: "512 bytes", "1.5MB". Units of 1024, one decimal
    place rounded half up only when the size is not a whole number of the
    unit; a size that rounds up to 1024 of a unit is one of the next."""
    if isinstance(bytes, bool) or not isinstance(bytes, int):
        raise ValueError("size must be a whole number of bytes, got %r" % (bytes,))
    if bytes < 0:
        raise ValueError("size must be 0 or more, got %d" % bytes)
    if bytes == 1:
        return "1 byte"
    if bytes < 1024:
        return "%d bytes" % bytes
    power = 1
    while power < len(UNITS) and bytes >= 1024 ** (power + 1):
        power += 1
    unit = 1024 ** power
    tenths = (bytes * 10 + unit // 2) // unit
    if tenths >= 10240 and power < len(UNITS):
        power += 1
        unit = 1024 ** power
        tenths = (bytes * 10 + unit // 2) // unit
    whole, fraction = divmod(tenths, 10)
    if fraction == 0:
        return "%d%s" % (whole, UNITS[power - 1])
    return "%d.%d%s" % (whole, fraction, UNITS[power - 1])

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and nothing else, 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.file-check

That builds the whole group. To build only what you call, and whatever it uses inside the group:

fune add form.file-check --only validateFiles
Download for Python form.file-check-1.0.0-python.fune · 33,339 bytes sha256 f501e12b2546d5c4081d3e4d7f66d32b047ff2535c575d064b4fe9b65c43f9db

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

The whole function, every language, is one file too: form.file-check-1.0.0.fune, 52,505 bytes, sha256 659728385e8393ded5292568174bfe73320f1fb76a50279c8b6bcc44a02e5db3. 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.file-check.validateFiles
# fune: before form.file-check.acceptsFile
# fune: before form.file-check.formatFileSize

after — your function gets the result and the arguments, and returns the final result.

# fune: after form.file-check.validateFiles
# fune: after form.file-check.acceptsFile
# fune: after form.file-check.formatFileSize

replace — it requires no other capability, so there is no dependency to replace.

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.file-check --steps.

# fune: step form.file-check.<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.

validateFiles 22 tests

CaseArgumentsExpected
nothing chosen in a required field: Select a file , required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message Select a file, errors ×1
nothing chosen in an optional field is valid , required false, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid true, message —, errors
one PDF within the size limit files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid true, message —, errors
exactly the size limit is allowed files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid true, message —, errors
the wrong type: The selected file must be a PDF files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file must be a PDF, errors ×1
an empty file files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file is empty, errors ×1
one byte over the limit, said in MB files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file must be 2MB or smaller, errors ×1
two files where one is allowed: the field's error first, then each file's by name files ×2, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message Select only one file, errors ×2
several files: too many, then a wrong type and one too large, each named files ×3, required true, accept .pdf,.jpg,image/png, max bytes 1,048,576, multiple true, max files 2 → valid false, message You can only select up to 2 files, errors ×3
up to 1 file, singular files ×2, required true, accept .pdf, max bytes 2,097,152, multiple true, max files 1 → valid false, message You can only select up to 1 file, errors ×1
Show the other 12 tests
CaseArgumentsExpected
several allowed and none chosen: Select at least one file , required true, accept .pdf, max bytes 2,097,152, multiple true, max files — → valid false, message Select at least one file, errors ×1
a wildcard is described as a word: an image files ×1, required true, accept image/*, max bytes —, multiple false, max files — → valid false, message The selected file must be an image, errors ×1
initialisms said letter by letter: an SVG or MP4 files ×1, required true, accept .svg, .mp4, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file must be an SVG or MP4, errors ×1
an extension and its MIME type are one PDF in the message files ×1, required true, accept .pdf,application/pdf, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file must be a PDF, errors ×1
a file gets one error: the wrong type beats empty files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid false, message The selected file must be a PDF, errors ×1
no accept and no limit: only empty files are refused files ×2, required true, accept —, max bytes —, multiple true, max files — → valid false, message zero.bin is empty, errors ×1
the accept check ignores case files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → valid true, message —, errors
maxFiles without multiple is the caller's mistake , required true, accept .pdf, max bytes 2,097,152, multiple false, max files 3 → error: rules.maxFiles only applies when rules.multiple is true
maxFiles below 1 , required true, accept .pdf, max bytes 2,097,152, multiple true, max files 0 → error: rules.maxFiles must be at least 1
a negative maxBytes , required true, accept .pdf, max bytes -1, multiple false, max files — → error: rules.maxBytes must be a size of 0 or more
a negative file size files ×1, required true, accept .pdf, max bytes 2,097,152, multiple false, max files — → error: file size must be a whole number of bytes, 0 or more
a malformed accept token , required true, accept pdf, max bytes 2,097,152, multiple false, max files — → error: accept token "pdf"

acceptsFile 14 tests

CaseArgumentsExpected
by extension, ignoring case .pdf, name report.PDF, size 1, mime type application/pdf → true
the extension must end the name .pdf, name report.pdf.exe, size 1, mime type → false
a type/* wildcard matches the MIME type image/*, name photo.heic, size 1, mime type image/heic → true
a wildcard needs a MIME type: none was guessed image/*, name photo.jpg, size 1, mime type → false
an exact MIME type, ignoring case application/pdf, name x.bin, size 1, mime type Application/PDF → true
an empty accept takes anything , name anything.exe, size 1, mime type application/x-msdownload → true
tokens are trimmed, and any one matching is enough .csv , text/csv , name data.txt, size 1, mime type text/csv → true
.jpg does not match a .jpeg file .jpg,.png, name a.jpeg, size 1, mime type image/jpeg → false
empty tokens are dropped, as browsers drop them .pdf,,, name a.pdf, size 1, mime type → true
an upper-case wildcard IMAGE/*, name p.png, size 1, mime type image/png → true
Show the other 4 tests
CaseArgumentsExpected
image/* does not match imagex/png image/*, name p.png, size 1, mime type imagex/png → false
a bare word is not a token pdf, name a.pdf, size 1, mime type → error: accept token "pdf"
a type with no subtype image/, name a.png, size 1, mime type image/png → error: accept token "image/"
a dot alone ., name a.png, size 1, mime type → error: accept token

formatFileSize 16 tests

CaseArgumentsExpected
nothing 0 → 0 bytes
one byte, singular 1 → 1 byte
just under a kilobyte 1,023 → 1023 bytes
exactly 1KB 1,024 → 1KB
1.5KB 1,536 → 1.5KB
1100 bytes is 1.07KB, so 1.1KB 1,100 → 1.1KB
1.25KB exactly rounds half up to 1.3KB 1,280 → 1.3KB
2MB 2,097,152 → 2MB
1,500,000 bytes is 1.43MB, so 1.4MB 1,500,000 → 1.4MB
one byte short of 1MB rounds up to 1MB, not 1024KB 1,048,575 → 1MB
Show the other 6 tests
CaseArgumentsExpected
one byte short of 10MB is 10MB 10,485,759 → 10MB
5TB 5,497,558,138,880 → 5TB
past terabytes stays in TB 1,125,899,906,842,624 → 1024TB
the largest safe integer 9,007,199,254,740,991 → 8192TB
a negative size -1 → error: size must be 0 or more
a fraction of a byte 1.5 → error: size must be a whole number of bytes

Verification

Verified by the operator, not the sandbox 52 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, in order

1. **The field.** Nothing chosen and `required`: "Select a file" ("Select at least one file" when `multiple`). More than one file when not `multiple`: "Select only one file". More than `maxFiles`: "You can only select up to 5 files". At most one field error, `index` -1, first in `errors`. 2. **Each file**, at most one error each, in this order: not accepted ("must be a PDF"), empty ("is empty"), larger than `maxBytes` ("must be 2MB or smaller"). A lone file is "The selected file"; when several are chosen each message starts with the file's name, so the person can tell which.

`message` is the first error's, for an error summary; `valid` is `errors` being empty. The wording follows the GOV.UK Design System's file upload component.

## accept

`acceptsFile` reads an accept attribute the way a browser's file chooser does: comma-separated tokens, trimmed, compared ignoring ASCII case; `.pdf` matches a name ending in `.pdf`; `application/pdf` matches the browser's MIME type exactly; `image/*` matches any `image/` type. An empty accept (or null in the rules) takes anything. A token that is none of these (`pdf`, `image/`) throws, because a typo would let every file through on the server while the browser hid them.

The browser's MIME type is a guess from the extension and may be empty, so a wildcard alone refuses a file the browser could not type; list the extensions too (`image/*,.heic`).

The message names the accepted types: an extension or a MIME subtype upper-cased (`.pdf` and `application/pdf` are both "PDF", once), a wildcard as its word ("image"), joined "a PDF, JPG or PNG". The article follows how it is said: "an image", "an SVG", "an MP4", "a PDF".

**This checks what the browser says about a file, not the file.** The name, size and type come from the person's computer. Check the stored object's real size and content (the upload-scanning gap in the saas-starter suite) before trusting it.

## formatFileSize

Units of 1024 (KB, MB, GB, TB), as file choosers show sizes, with one decimal place rounded half up only when the size is not whole: 1536 is "1.5KB", 2097152 is "2MB", 1 is "1 byte". A size that rounds to 1024 of a unit is written as one of the next (1048575 bytes is "1MB", not "1024KB"). Integer arithmetic only, so every language prints the same. The size limit in the too-large message is written with it.

## Errors

Thrown, since they are the caller's mistakes: a negative `maxBytes`, a `maxFiles` below 1 or without `multiple`, a malformed accept token, a negative or fractional file size.

## 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,213
README.md3,599
impl/python/accepts_file.py3,266
impl/python/format_file_size.py1,111
impl/python/validate_files.py2,940
impl/rust/accepts_file.rs3,915
impl/rust/format_file_size.rs1,462
impl/rust/validate_files.rs4,649
impl/typescript/accepts_file.ts4,153
impl/typescript/format_file_size.ts1,269
impl/typescript/validate_files.ts2,736
vectors.json12,407