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
| Parameter | Type | Description |
|---|---|---|
options.maxSize | number | Maximum size in bytes: 2 * 1024 * 1024 |
options.types | string[] | MIME types, groups and extensions: ['image/*', 'application/pdf', '.docx'] |
msg | Message | Custom message for all file errors |
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty and the field is required | Required |
file | Not a file | Must be a file |
fileSize | The file is larger than maxSize | File must be at most {max} |
fileType | The type is not in the list | File type must be one of: {types} |
You can change the texts: see Messages & i18n.
Notes
- Works in the browser and in Node 20+ — there
Filecomes fromFormData(request.formData()in fetch, Hono, Nuxt). - In the message
{max}is a readable size:2 MB. The errorparamsalso havesize— the file size. - Extensions are case-insensitive:
.pdfacceptsDOC.PDF. - Several files —
arraywithmaxLength.
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);
});