HTML Input File Accept Attribute Checker

2.2.5 · active · verified Sun Apr 19

attr-accept is a lightweight JavaScript utility that implements the logic of the HTML5 `<input type="file">` `accept` attribute. It provides a function to programmatically check if a given `File` object matches the criteria specified by an `accept` string, which can include MIME types (e.g., `image/*`, `application/pdf`), file extensions (e.g., `.jpg`, `.png`), and wildcards. The current stable version is 2.2.5. The library maintains a steady, though not rapid, release cadence, primarily focusing on bug fixes and minor improvements. Its key differentiator is providing a robust, standalone, and browser-compatible implementation of a browser's native file acceptance logic, making it suitable for custom file upload components, especially in libraries like react-dropzone.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to use the `attrAccept` function to validate different file types against various 'accept' attribute strings, including MIME types, extensions, and wildcards.

import attrAccept from 'attr-accept';

interface MyFile extends File {
  path?: string;
}

// Example 1: Check a JPEG file against an image accept string
const jpegFile: MyFile = new File([''], 'test.jpeg', { type: 'image/jpeg' });
const acceptsImages = attrAccept(jpegFile, 'image/*');
console.log(`'test.jpeg' accepts 'image/*': ${acceptsImages}`); // true

// Example 2: Check a PDF file against multiple accept types
const pdfFile: MyFile = new File([''], 'document.pdf', { type: 'application/pdf' });
const acceptsDocs = attrAccept(pdfFile, '.pdf, application/msword');
console.log(`'document.pdf' accepts '.pdf, application/msword': ${acceptsDocs}`); // true

// Example 3: Check a text file against a specific extension
const txtFile: MyFile = new File([''], 'notes.txt', { type: 'text/plain' });
const acceptsPng = attrAccept(txtFile, '.png');
console.log(`'notes.txt' accepts '.png': ${acceptsPng}`); // false

// Example 4: Accepting all files if the accept string is empty or undefined (or empty array)
const anyFile: MyFile = new File([''], 'data.json', { type: 'application/json' });
const acceptsAny = attrAccept(anyFile, ''); // or undefined, or []
console.log(`'data.json' accepts an empty accept string: ${acceptsAny}`); // true (since v2.2.3)

view raw JSON →