Skip to content

file ​

A file from <input type="file"> or FormData: size and type.

Signature ​

ts
function file(options?: { maxSize?: number; types?: string[] }, msg?: Message): Schema<File>

Parameters ​

ParameterTypeDescription
options.maxSizenumberMaximum size in bytes: 2 * 1024 * 1024
options.typesstring[]MIME types, groups and extensions: ['image/*', 'application/pdf', '.docx']
msgMessageCustom message for all file errors

Error codes ​

CodeWhenDefault message
requiredThe value is empty and the field is requiredRequired
fileNot a fileMust be a file
fileSizeThe file is larger than maxSizeFile must be at most {max}
fileTypeThe type is not in the listFile type must be one of: {types}

You can change the texts: see Messages & i18n.

Notes ​

  • Works in the browser and in Node 20+ — there File comes from FormData (request.formData() in fetch, Hono, Nuxt).
  • In the message {max} is a readable size: 2 MB. The error params also have size — the file size.
  • Extensions are case-insensitive: .pdf accepts DOC.PDF.
  • Several files — array with maxLength.

Examples ​

Avatar ​

ts
const avatar = file({ maxSize: 2 * 1024 * 1024, types: ['image/*'] });

Several documents ​

ts
const Application = object({
  documents: pipe(array(file({ types: ['application/pdf', '.docx'] })), minLength(1), maxLength(5)),
});

On the server ​

ts
app.post('/upload', async (c) => {
  const form = Object.fromEntries(await c.req.formData());
  const { avatar } = parse(object({ avatar: file({ maxSize: 2 * 1024 * 1024 }) }), form);
});

See also ​