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.
- validate_files (files: FileInfo[], rules: FileRules) -> FileCheck
- accepts_file (accept: string, file: FileInfo) -> bool
- format_file_size (bytes: int) -> string
The types it declares, generated into your project
/// One chosen file, as the browser describes it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileInfo {
/// the file's name, such as report.pdf
pub name: String,
/// bytes
pub size: i64,
/// the MIME type the browser guessed (File.type); may be ""
pub mime_type: String,
}
/// What a file upload field requires.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileRules {
/// at least one file must be chosen
pub required: bool,
/// an accept attribute; null or empty accepts any file
pub accept: Option<String>,
/// the largest size allowed for each file
pub max_bytes: Option<i64>,
/// more than one file may be chosen
pub multiple: bool,
/// the most files allowed when multiple
pub max_files: Option<i64>,
}
/// One error: the field's (index -1) or one file's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileError {
/// the file's position in files, or -1 for the field as a whole
pub index: i64,
/// the file's name, null for the field
pub name: Option<String>,
/// required, one-file, too-many, type, too-large or empty
pub code: String,
/// what is wrong, to show
pub message: String,
}
/// The verdict on a file upload field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileCheck {
pub valid: bool,
/// the first error's message, for the error summary
pub message: Option<String>,
/// every error, the field's first, then each file's in order; empty when valid
pub errors: Vec<FileError>,
}
Once installed, your code imports each one from the group's module.
validate_files throws on bad input 22 tests
pub fn validate_files(files: &[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
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 filevalidate_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 validvalidate_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
fune!(form.file-check@^1); // then call validate_files(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
use super::form_file_check_accepts_file::{accept_tokens, describe_accept, file_info_from_value, matches_accept}; ← acceptsFile, another function of this group · built into the same file, even by a slim install
use super::form_file_check_format_file_size::format_file_size; ← formatFileSize, another function of this group · built into the same file, even by a slim install
/// 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).
///
/// # Panics
/// Panics on bad rules (negative maxBytes, maxFiles below 1 or without
/// multiple), a malformed accept token, or a negative file size.
pub fn validate_files(files: &[FileInfo], rules: &FileRules) -> FileCheck {
if let Some(max) = rules.max_bytes {
if max < 0 {
panic!("rules.maxBytes must be a size of 0 or more, got {}", max);
}
}
if let Some(max) = rules.max_files {
if !rules.multiple {
panic!("rules.maxFiles only applies when rules.multiple is true");
}
if max < 1 {
panic!("rules.maxFiles must be at least 1, got {}", max);
}
}
let tokens = accept_tokens(rules.accept.as_deref().unwrap_or(""));
for file in files {
if file.size < 0 {
panic!("file size must be a whole number of bytes, 0 or more, got {} for \"{}\"", file.size, file.name);
}
}
let mut errors: Vec<FileError> = Vec::new();
let field = |code: &str, message: String| FileError { index: -1, name: None, code: code.to_string(), message };
if files.is_empty() {
if rules.required {
let message = if rules.multiple { "Select at least one file" } else { "Select a file" };
errors.push(field("required", message.to_string()));
}
} else if !rules.multiple && files.len() > 1 {
errors.push(field("one-file", "Select only one file".to_string()));
} else if let Some(max) = rules.max_files {
if files.len() as i64 > max {
let noun = if max == 1 { "file" } else { "files" };
errors.push(field("too-many", format!("You can only select up to {} {}", max, noun)));
}
}
for (index, file) in files.iter().enumerate() {
let subject = if files.len() == 1 { "The selected file" } else { file.name.as_str() };
let found = if !matches_accept(&tokens, file) {
Some(("type", format!("{} must be {}", subject, describe_accept(&tokens))))
} else if file.size == 0 {
Some(("empty", format!("{} is empty", subject)))
} else {
match rules.max_bytes {
Some(max) if file.size > max => {
Some(("too-large", format!("{} must be {} or smaller", subject, format_file_size(max))))
}
_ => None,
}
};
if let Some((code, message)) = found {
errors.push(FileError { index: index as i64, name: Some(file.name.clone()), code: code.to_string(), message });
}
}
let message = errors.first().map(|e| e.message.clone());
FileCheck { valid: errors.is_empty(), message, errors }
}
pub fn file_check_to_value(check: &FileCheck) -> Value {
let text = |v: &Option<String>| v.as_deref().map(Value::str).unwrap_or(Value::Null);
Value::obj(vec![
("valid", Value::Bool(check.valid)),
("message", text(&check.message)),
(
"errors",
Value::Arr(
check
.errors
.iter()
.map(|e| {
Value::obj(vec![
("index", Value::Int(e.index)),
("name", text(&e.name)),
("code", Value::str(&e.code)),
("message", Value::str(&e.message)),
])
})
.collect(),
),
),
])
}
pub fn fune_vector(args: &[Value]) -> Value {
let files: Vec<FileInfo> = args[0].as_arr().iter().map(file_info_from_value).collect();
let r = &args[1];
let int = |key: &str| match r.get(key) {
Value::Int(n) => Some(*n),
Value::Null => None,
other => panic!("rules.{} must be a whole number, got {:?}", key, other),
};
let rules = FileRules {
required: r.get("required").as_bool(),
accept: match r.get("accept") {
Value::Str(s) => Some(s.clone()),
_ => None,
},
max_bytes: int("maxBytes"),
multiple: r.get("multiple").as_bool(),
max_files: int("maxFiles"),
};
file_check_to_value(&validate_files(&files, &rules))
}accepts_file throws on bad input 14 tests
pub fn accepts_file(accept: &str, file: &FileInfo) -> bool
| 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
accepts_file(.pdf, name report.PDF, size 1, mime type application/pdf)→ true by extension, ignoring caseaccepts_file(.pdf, name report.pdf.exe, size 1, mime type )→ false the extension must end the nameaccepts_file(image/*, name photo.heic, size 1, mime type image/heic)→ true a type/* wildcard matches the MIME type
fune!(form.file-check@^1); // then call accepts_file(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
fn is_space(c: char) -> bool {
matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b')
}
// RFC 6838's restricted-name characters.
fn is_mime_name(value: &str) -> bool {
!value.is_empty() && value.chars().all(|c| c.is_ascii_alphanumeric() || "!#$&^_.+-".contains(c))
}
/// The accept attribute's tokens, trimmed and lower-cased, empty ones dropped.
///
/// # Panics
/// Panics on a token that is not an extension, a MIME type or a type/* wildcard.
pub fn accept_tokens(accept: &str) -> Vec<String> {
let mut tokens = Vec::new();
for raw in accept.split(',') {
let trimmed = raw.trim_matches(is_space);
let token = trimmed.to_ascii_lowercase();
if token.is_empty() {
continue;
}
let ok = if let Some(ext) = token.strip_prefix('.') {
!ext.is_empty() && !ext.contains('/') && !ext.chars().any(is_space)
} else {
match token.find('/') {
Some(slash) if slash > 0 => {
let (kind, subtype) = (&token[..slash], &token[slash + 1..]);
is_mime_name(kind) && (subtype == "*" || is_mime_name(subtype))
}
_ => false,
}
};
if !ok {
panic!(
"accept token \"{}\" is not an extension (.pdf), a MIME type (application/pdf) or a wildcard (image/*)",
trimmed
);
}
tokens.push(token);
}
tokens
}
/// What the accepted types are called in an error message: "a PDF", "an
/// image", "a PDF, JPG or PNG".
pub fn describe_accept(tokens: &[String]) -> String {
let mut words: Vec<String> = Vec::new();
for token in tokens {
let word = if let Some(ext) = token.strip_prefix('.') {
ext.to_ascii_uppercase()
} else if let Some(kind) = token.strip_suffix("/*") {
kind.to_string()
} else {
token[token.find('/').map(|i| i + 1).unwrap_or(0)..].to_ascii_uppercase()
};
if !words.contains(&word) {
words.push(word);
}
}
let listed = if words.len() == 1 {
words[0].clone()
} else {
format!("{} or {}", words[..words.len() - 1].join(", "), words[words.len() - 1])
};
let first = words[0].chars().next().unwrap_or(' ');
// A lower-case word is said as a word; an initialism letter by letter.
let an = if first.is_ascii_lowercase() { "aeiou".contains(first) } else { "AEFHILMNORSX8".contains(first) };
format!("{} {}", if an { "an" } else { "a" }, listed)
}
pub fn matches_accept(tokens: &[String], file: &FileInfo) -> bool {
if tokens.is_empty() {
return true;
}
let name = file.name.to_ascii_lowercase();
let kind = file.mime_type.to_ascii_lowercase();
tokens.iter().any(|token| {
if token.starts_with('.') {
name.ends_with(token.as_str())
} else if let Some(prefix) = token.strip_suffix('*') {
kind.starts_with(prefix)
} else {
kind == *token
}
})
}
/// 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.
///
/// # Panics
/// Panics on a malformed accept token.
pub fn accepts_file(accept: &str, file: &FileInfo) -> bool {
matches_accept(&accept_tokens(accept), file)
}
pub fn file_info_from_value(v: &Value) -> FileInfo {
let size = match v.get("size") {
Value::Int(n) => *n,
other => panic!("file size must be a whole number of bytes, got {:?}", other),
};
FileInfo { name: v.get("name").as_str().to_string(), size, mime_type: v.get("mimeType").as_str().to_string() }
}
pub fn fune_vector(args: &[Value]) -> Value {
Value::Bool(accepts_file(args[0].as_str(), &file_info_from_value(&args[1])))
}format_file_size throws on bad input 16 tests
pub fn format_file_size(bytes: i64) -> 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
format_file_size(0)→ 0 bytes nothingformat_file_size(1)→ 1 byte one byte, singularformat_file_size(1,023)→ 1023 bytes just under a kilobyte
fune!(form.file-check@^1); // then call format_file_size(…)
Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.
use super::funejson::Value; ← the fune runtime: the JSON value the test vectors use; fune build keeps it only where a signature takes one
const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
/// 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.
///
/// # Panics
/// Panics on a negative size.
pub fn format_file_size(bytes: i64) -> String {
if bytes < 0 {
panic!("size must be 0 or more, got {}", bytes);
}
if bytes == 1 {
return "1 byte".to_string();
}
if bytes < 1024 {
return format!("{} bytes", bytes);
}
let b = bytes as i128;
let mut power: u32 = 1;
while (power as usize) < UNITS.len() && b >= 1024i128.pow(power + 1) {
power += 1;
}
let mut unit = 1024i128.pow(power);
let mut tenths = (b * 10 + unit / 2) / unit;
if tenths >= 10240 && (power as usize) < UNITS.len() {
power += 1;
unit = 1024i128.pow(power);
tenths = (b * 10 + unit / 2) / unit;
}
let (whole, fraction) = (tenths / 10, tenths % 10);
if fraction == 0 {
format!("{}{}", whole, UNITS[power as usize - 1])
} else {
format!("{}.{}{}", whole, fraction, UNITS[power as usize - 1])
}
}
pub fn fune_vector(args: &[Value]) -> Value {
if let Value::Float(f) = args[0] {
panic!("size must be a whole number of bytes, got {}", f);
}
Value::str(&format_file_size(args[0].as_i64()))
}Install
fune build
With that line in your source, in a Rust project (language rust in fune.project), fune build resolves it and nothing else, pins them in fune.lock, downloads only the Rust 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. A crate’s build.rs runs it before every compile. 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 Rust implementation. Install it without the registry with fune add ./form.file-check-1.0.0-rust.fune, or fetch it from a terminal with fune pull form.file-check@1.0.0:rust.
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.