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.
- validateFiles (files: FileInfo[], rules: FileRules) -> FileCheck
- acceptsFile (accept: string, file: FileInfo) -> bool
- formatFileSize (bytes: int) -> string
The types it declares, generated into your project
/** One chosen file, as the browser describes it. */
export interface FileInfo {
/** the file's name, such as report.pdf */
readonly name: string;
/** bytes */
readonly size: number;
/** the MIME type the browser guessed (File.type); may be "" */
readonly mimeType: string;
}
/** What a file upload field requires. */
export interface FileRules {
/** at least one file must be chosen */
readonly required: boolean;
/** an accept attribute; null or empty accepts any file */
readonly accept: string | null;
/** the largest size allowed for each file */
readonly maxBytes: number | null;
/** more than one file may be chosen */
readonly multiple: boolean;
/** the most files allowed when multiple */
readonly maxFiles: number | null;
}
/** One error: the field's (index -1) or one file's. */
export interface FileError {
/** the file's position in files, or -1 for the field as a whole */
readonly index: number;
/** the file's name, null for the field */
readonly name: string | null;
/** required, one-file, too-many, type, too-large or empty */
readonly code: string;
/** what is wrong, to show */
readonly message: string;
}
/** The verdict on a file upload field. */
export interface FileCheck {
readonly valid: boolean;
/** the first error's message, for the error summary */
readonly message: string | null;
/** every error, the field's first, then each file's in order; empty when valid */
readonly errors: readonly FileError[];
}
Once installed, your code imports each one from the group's module.
validateFiles throws on bad input 22 tests
export function validateFiles(files: readonly FileInfo[], rules: FileRules): FileCheck
| files | FileInfo[] | what was chosen: each file's name, size in bytes and MIME type, as the browser's File gives them |
| rules | FileRules | accept, size limit and how many files |
| returns | FileCheck | valid, or every error: the field's, and each file's |
For example
validateFiles(, 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 filevalidateFiles(, required false, accept .pdf, max bytes 2,097,152, multiple false, max files —)→ valid true, message —, errors nothing chosen in an optional field is validvalidateFiles(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
import { validateFiles } from "#fune/form.file-check@^1";
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
import { acceptTokens, describeAccept, matchesAccept } from "./form_file_check_accepts_file.ts"; ← acceptsFile, another function of this group · built into the same file, even by a slim install
import { formatFileSize } from "./form_file_check_format_file_size.ts"; ← formatFileSize, another function of this group · built into the same file, even by a slim install
import type { FileCheck, FileError, FileInfo, FileRules } from "./form_file_check_types.ts";
/**
* 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 (nothing chosen,
* too many), then each file's, at most one each (its type, then empty, then
* too large). A single file is "The selected file"; when several are chosen,
* each message names its file.
*/
export function validateFiles(files: readonly FileInfo[], rules: FileRules): FileCheck {
// The rules are the caller's, so a bad one fails loudly whatever was chosen.
if (rules.maxBytes != null && (!Number.isSafeInteger(rules.maxBytes) || rules.maxBytes < 0)) {
throw new RangeError(`rules.maxBytes must be a size of 0 or more, got ${rules.maxBytes}`);
}
if (rules.maxFiles != null) {
if (!rules.multiple) throw new RangeError("rules.maxFiles only applies when rules.multiple is true");
if (!Number.isSafeInteger(rules.maxFiles) || rules.maxFiles < 1) throw new RangeError(`rules.maxFiles must be at least 1, got ${rules.maxFiles}`);
}
const tokens = acceptTokens(rules.accept ?? "");
for (const file of files) {
if (!Number.isSafeInteger(file.size) || file.size < 0) throw new RangeError(`file size must be a whole number of bytes, 0 or more, got ${file.size} for "${file.name}"`);
}
const errors: FileError[] = [];
const field = (code: string, message: string) => errors.push({ index: -1, name: null, code, message });
if (files.length === 0) {
if (rules.required) field("required", rules.multiple ? "Select at least one file" : "Select a file");
} else if (!rules.multiple && files.length > 1) {
field("one-file", "Select only one file");
} else if (rules.maxFiles != null && files.length > rules.maxFiles) {
field("too-many", `You can only select up to ${rules.maxFiles} ${rules.maxFiles === 1 ? "file" : "files"}`);
}
files.forEach((file, index) => {
const subject = files.length === 1 ? "The selected file" : file.name;
const add = (code: string, message: string) => errors.push({ index, name: file.name, code, message });
if (!matchesAccept(tokens, file)) add("type", `${subject} must be ${describeAccept(tokens)}`);
else if (file.size === 0) add("empty", `${subject} is empty`);
else if (rules.maxBytes != null && file.size > rules.maxBytes) add("too-large", `${subject} must be ${formatFileSize(rules.maxBytes)} or smaller`);
});
return { valid: errors.length === 0, message: errors.length > 0 ? errors[0].message : null, errors };
}acceptsFile throws on bad input 14 tests
export function acceptsFile(accept: string, file: FileInfo): boolean
| accept | string | an accept attribute: comma-separated extensions (.pdf), MIME types (application/pdf) and wildcards (image/*); empty accepts anything |
| file | FileInfo | the file to test |
| returns | bool | whether the browser's file chooser would offer it |
For example
acceptsFile(.pdf, name report.PDF, size 1, mime type application/pdf)→ true by extension, ignoring caseacceptsFile(.pdf, name report.pdf.exe, size 1, mime type )→ false the extension must end the nameacceptsFile(image/*, name photo.heic, size 1, mime type image/heic)→ true a type/* wildcard matches the MIME type
import { acceptsFile } from "#fune/form.file-check@^1";
import type { FileInfo } from "./form_file_check_types.ts";
// ASCII only, so all three languages fold and trim the same characters.
function lower(value: string): string {
return value.replace(/[A-Z]/g, (c) => c.toLowerCase());
}
function upper(value: string): string {
return value.replace(/[a-z]/g, (c) => c.toUpperCase());
}
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);
}
// RFC 6838's restricted-name characters: a type or subtype is made of these.
function isMimeName(value: string): boolean {
if (value === "") return false;
for (const ch of value) {
const ok = (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z") || (ch >= "0" && ch <= "9") || "!#$&^_.+-".includes(ch);
if (!ok) return false;
}
return true;
}
/**
* The accept attribute's tokens, trimmed and lower-cased, empty ones dropped
* (as browsers drop them). Anything that is not an extension, a MIME type or
* a type/* wildcard throws: a typo in accept would otherwise let every file
* through on the server while the browser hides them.
*/
export function acceptTokens(accept: string): string[] {
const tokens: string[] = [];
for (const raw of accept.split(",")) {
const token = lower(trim(raw));
if (token === "") continue;
let ok = false;
if (token.startsWith(".")) {
const ext = token.slice(1);
ok = ext !== "" && !ext.includes("/") && ![...ext].some(isSpace);
} else {
const slash = token.indexOf("/");
if (slash > 0) {
const type = token.slice(0, slash);
const subtype = token.slice(slash + 1);
ok = isMimeName(type) && (subtype === "*" || isMimeName(subtype));
}
}
// Tokens are checked, so only a wildcard ends in "*". The code never
// spells slash-star: fune reads exports with block comments blanked.
if (!ok) throw new RangeError(`accept token "${trim(raw)}" is not an extension (.pdf), a MIME type (application/pdf) or a wildcard (image/` + "*)");
tokens.push(token);
}
return tokens;
}
/**
* What the accepted types are called in an error message: ".pdf" and
* "application/pdf" are both "PDF", "image/*" is "image"; repeats dropped,
* then "a PDF", "an image", "a PDF, JPG or PNG".
*/
export function describeAccept(tokens: readonly string[]): string {
const words: string[] = [];
for (const token of tokens) {
let word: string;
if (token.startsWith(".")) word = upper(token.slice(1));
else if (token.endsWith("*")) word = token.slice(0, -2);
else word = upper(token.slice(token.indexOf("/") + 1));
if (!words.includes(word)) words.push(word);
}
const head = words.slice(0, -1).join(", ");
const list = words.length === 1 ? words[0] : head + " or " + words[words.length - 1];
const first = words[0][0];
// A lower-case word is said as a word; an initialism letter by letter, so
// "an SVG" and "an MP4" but "a PDF".
const an = first >= "a" && first <= "z" ? "aeiou".includes(first) : "AEFHILMNORSX8".includes(first);
return (an ? "an " : "a ") + list;
}
export function matchesAccept(tokens: readonly string[], file: FileInfo): boolean {
if (tokens.length === 0) return true;
const name = lower(file.name);
const type = lower(file.mimeType);
for (const token of tokens) {
if (token.startsWith(".")) {
if (name.endsWith(token)) return true;
} else if (token.endsWith("*")) {
if (type.startsWith(token.slice(0, -1))) return true;
} else if (type === token) {
return true;
}
}
return false;
}
/**
* Whether a browser's file chooser would offer this file for an accept
* attribute: by extension (case-insensitive), by exact MIME type, or by a
* type/* wildcard. An empty accept takes anything.
*/
export function acceptsFile(accept: string, file: FileInfo): boolean {
return matchesAccept(acceptTokens(accept), file);
}formatFileSize throws on bad input 16 tests
export function formatFileSize(bytes: number): string
| bytes | int | a size in bytes, 0 or more |
| returns | string | "512 bytes", "1KB", "1.5MB", "2GB": units of 1024, one decimal place when not whole |
For example
formatFileSize(0)→ 0 bytes nothingformatFileSize(1)→ 1 byte one byte, singularformatFileSize(1,023)→ 1023 bytes just under a kilobyte
import { formatFileSize } from "#fune/form.file-check@^1";
const UNITS = ["KB", "MB", "GB", "TB"];
/**
* A size for people: "512 bytes", "1.5MB". Units of 1024, as operating
* systems' file choosers show them, and 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 written as one of the next (1048575 bytes is "1MB").
* Integer arithmetic throughout (BigInt here), so every language agrees.
*/
export function formatFileSize(bytes: number): string {
if (!Number.isSafeInteger(bytes)) throw new RangeError(`size must be a whole number of bytes, got ${bytes}`);
if (bytes < 0) throw new RangeError(`size must be 0 or more, got ${bytes}`);
if (bytes === 1) return "1 byte";
if (bytes < 1024) return `${bytes} bytes`;
const b = BigInt(bytes);
let power = 1;
while (power < UNITS.length && b >= 1024n ** BigInt(power + 1)) power++;
let unit = 1024n ** BigInt(power);
let tenths = (b * 10n + unit / 2n) / unit;
if (tenths >= 10240n && power < UNITS.length) {
power++;
unit = 1024n ** BigInt(power);
tenths = (b * 10n + unit / 2n) / unit;
}
const whole = tenths / 10n;
const fraction = tenths % 10n;
return fraction === 0n ? `${whole}${UNITS[power - 1]}` : `${whole}.${fraction}${UNITS[power - 1]}`;
}Install
fune build
With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and nothing else, 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.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
The manifest, vectors and README with only the TypeScript implementation. Install it without the registry with fune add ./form.file-check-1.0.0-typescript.fune, or fetch it from a terminal with fune pull form.file-check@1.0.0:typescript.
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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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
| Case | Arguments | Expected | |
|---|---|---|---|
| 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.