
Input accept Attribute Doesn't Validate File Types: Fix It
The input accept attribute does not validate file types. MDN puts it plainly: accept "doesn't validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types." A visitor can switch the chooser to all files, and a script can hand the input any file at all. Check the type in JavaScript for a quick error, and on the server for the real decision.
You'll run a demo that gets a .txt file into an accept=".pdf" input two different ways. Then you'll build the checks that do work in the browser: extension, file.type, and the file's first bytes. Each one has a known gap, and the post shows where it is. The last part covers what a server has to enforce, and what our own form backend, Static Forms, does and doesn't check.
If you need the file input basics first (multiple, capture, styling, C:\fakepath), start with the HTML file input reference. This post stays on one question: how do you make sure the file is the type you asked for? Sources were checked on 13 November 2026.
What accept does, according to the spec and MDN
accept takes a comma-separated list of what MDN calls unique file type specifiers. Each one is a file extension that starts with a period (.pdf), a MIME type (application/pdf), or one of image/*, audio/* and video/*.
The HTML specification gives browsers a soft job: they "may use the value of this attribute to display a more appropriate user interface than a generic file picker", and they "should prevent the user from selecting files that are not accepted". The spec says should, so a browser that lets the filter be switched off still follows it. The same section reminds authors that data received from a client should be treated with caution even when the browser obeys accept.
MDN goes further. It says users can, in most cases, "toggle an option in the file chooser" that lets them pick any file, and that you "should make sure that expected requirement is validated server-side."
So accept is a filter on the chooser dialog. It never looks at a file after selection, and it doesn't stop a form from submitting.

Three ways a wrong file gets past accept
- The chooser's "All files" option. Most operating system choosers have a file type menu. Switch it from the filtered list to all files and pick anything. Where that option lives depends on the browser and operating system.
- Script assignment. The spec's setter for
input.filesdoes two things: if the value is not null, it replaces the selected files. It doesn't checkaccept, and it doesn't fire achangeevent. Any drop zone that doesinput.files = event.dataTransfer.fileswill put whatever was dropped into the input. The file input value guide covers that pattern in detail. - No browser at all. A
curlcommand or a script can post a multipart request straight to your endpoint. Your HTML never runs, so neitheracceptnor your JavaScript sees the file.
Honest visitors hit the first two by accident. The third is the reason a server check exists.
Demo: watch accept get bypassed
Save this as accept-bypass.html and open it in a browser. Nothing is uploaded. The input says accept=".pdf,application/pdf". Try two things:
- Click the input, switch the chooser to all files if your system offers that, and pick a
.txtor.pngfile. - Drag any file onto the dashed box. The script assigns it to the input with
input.files = ..., exactly as many drop zones do.
The page reports what ended up in the input and whether it matches the accept list.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>accept bypass demo</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 600px; margin: 2rem auto; padding: 0 1rem; }
#drop { border: 2px dashed #9ca3af; border-radius: 8px; padding: 2rem; text-align: center; margin: 1rem 0; }
#drop.over { border-color: #1f2937; background: #f3f4f6; }
pre { background: #f3f4f6; padding: 1rem; border-radius: 6px; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>Does accept stop this file?</h1>
<label for="doc">PDF only (accept=".pdf,application/pdf")</label>
<input id="doc" type="file" accept=".pdf,application/pdf">
<div id="drop">Or drop any file here</div>
<pre id="report" aria-live="polite">No file selected yet.</pre>
<script>
const input = document.getElementById('doc');
const drop = document.getElementById('drop');
const report = document.getElementById('report');
// The same matching rules a chooser filter uses: extensions, exact MIME types, and type/* wildcards
function matchesAccept(file, accept) {
const name = file.name.toLowerCase();
const type = file.type.toLowerCase();
return accept.split(',').map((token) => token.trim().toLowerCase()).some((token) => {
if (!token) return false;
if (token.startsWith('.')) return name.endsWith(token);
if (token.endsWith('/*')) return type.startsWith(token.slice(0, -1));
return type === token;
});
}
function describe(how) {
const file = input.files[0];
if (!file) {
report.textContent = 'No file selected yet.';
return;
}
report.textContent =
'How it arrived: ' + how + '\n' +
'Name: ' + file.name + '\n' +
'Size: ' + file.size + ' bytes\n' +
'file.type: "' + file.type + '"\n' +
'Matches accept: ' + (matchesAccept(file, input.accept) ? 'yes' : 'NO, and the input took it anyway');
}
input.addEventListener('change', () => describe('file chooser'));
drop.addEventListener('dragover', (event) => {
event.preventDefault();
drop.classList.add('over');
});
drop.addEventListener('dragleave', () => drop.classList.remove('over'));
drop.addEventListener('drop', (event) => {
event.preventDefault();
drop.classList.remove('over');
// The files setter does not check accept and does not fire change
input.files = event.dataTransfer.files;
describe('script assignment from a drop');
});
</script>
</body>
</html>The drop path matches what the spec says: the input holds a file that accept would have filtered out of the chooser, and no change event fired, so any validation you attached only to change never ran. If your drop zone assigns files this way, call your validation yourself right after the assignment.
Check the file type in JavaScript
A browser check gives honest visitors a readable error before they wait for an upload. There are three things you can look at, and none of them proves what the file is.
Extension: file.name
Matching the end of file.name against an allowlist (.pdf, .docx) is predictable and works on every system. It is also the easiest check to fool: rename notes.txt to notes.pdf and it passes.
MIME type: file.type
file.type looks like the stronger signal, but the browser doesn't read the file to set it. MDN's Blob.type page says the type is assumed from the file extension, that client configuration such as the Windows Registry can produce unexpected values even for common types, and that it is an empty string when the type can't be determined. Its advice: "Developers are advised not to rely on this property as a sole validation scheme."
Two practical consequences:
- A renamed file gets the MIME type of its new extension.
notes.pdfreportsapplication/pdf. - Rejecting an empty
file.typewill turn away some legitimate files on systems that don't map the extension. Prefer the extension check when the type is empty.
Magic bytes: the file's signature
Many formats start with a fixed signature. Every PDF begins with the ASCII text %PDF-. PNG files start with the bytes 89 50 4E 47 0D 0A 1A 0A, and JPEG files with FF D8 FF. Reading the first few bytes with file.slice(0, 8).arrayBuffer() catches the renamed text file that passes both checks above, without reading the whole file into memory.
It is still a browser check. A file can start with %PDF- and be broken or hostile after that, and a request that skips your page skips the check. Treat it as a better error message, not as proof.
A validation function that combines them
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Check a PDF in the browser</title>
</head>
<body>
<label for="doc">PDF document</label>
<input id="doc" type="file" accept=".pdf,application/pdf" aria-describedby="doc-error">
<p id="doc-error" role="alert"></p>
<script>
const input = document.getElementById('doc');
const error = document.getElementById('doc-error');
const PDF_SIGNATURE = '%PDF-';
async function checkPdf(file) {
if (!file.name.toLowerCase().endsWith('.pdf')) {
return 'Choose a file that ends in .pdf.';
}
// file.type comes from the extension and may be empty, so only reject a type that clearly disagrees
if (file.type && file.type !== 'application/pdf') {
return 'That file does not look like a PDF (' + file.type + ').';
}
const head = new Uint8Array(await file.slice(0, PDF_SIGNATURE.length).arrayBuffer());
const text = String.fromCharCode(...head);
if (text !== PDF_SIGNATURE) {
return 'That file ends in .pdf but its contents are not a PDF.';
}
return '';
}
input.addEventListener('change', async () => {
const file = input.files[0];
error.textContent = '';
input.setCustomValidity('');
if (!file) return;
const message = await checkPdf(file);
input.setCustomValidity(message);
error.textContent = message;
});
</script>
</body>
</html>Rename a .txt file to .pdf and pick it: the extension and file.type checks pass, and the signature check catches it.
Keep the browser error in sync with the selection
The original version of this post was about a bug that still catches people, so it stays. setCustomValidity() keeps an input invalid for as long as its message is non-empty. If you set an error for a bad file and never clear it, the next good file is still blocked.
Three rules avoid it:
- Start every check from an empty message. Call
input.setCustomValidity('')first, then set a message only if a check fails. The function above does that. - Validate on
change, not only on submit. An invalid input stops the browser from firingsubmitat all, so a handler that clears the error on submit never runs. - Clear your own state on reset. A form
resetempties the file input, but not your error text, youraria-invalidflag or a custom validity message. Listen forresetand clear them. The form reset and stale errors guide covers reset ordering for other field types.
An async check (like reading magic bytes) adds one gap: a visitor can press submit before the check finishes. The complete example below sets a "Checking the file" message first, so the input stays invalid until the result is in.
What the server has to enforce
Everything above runs on the visitor's machine. The server is the only place where a type rule holds, because it's the only check a request can't skip. On a receiver you control:
- Allowlist extensions and check the signature. Read the first bytes of the stored file, as the browser example does, and reject anything that doesn't match. Don't trust the
Content-Typeof the multipart part; the client sets it. - Limit size for the whole request, not just each file. A browser per-file check doesn't count the other fields or multipart overhead.
- Treat the file name as untrusted text. Generate your own storage name. Never use
file.nameas a path or drop it into HTML unescaped. - Don't serve uploads as live content. An uploaded
.htmlor.svgserved from your own domain runs in your origin. Serve files as downloads or from a separate domain. - Decide on scanning before the first upload arrives, if people will open these files.
What Static Forms checks, and what it doesn't
We make Static Forms, a form backend for static sites, so here is what it does with an uploaded file, from the file uploads docs:
- File type: not checked. The docs say so directly: "The server does not enforce file type validation." A PDF-only
accepton your form is a browser hint, not a Static Forms rule. If your workflow needs a verified PDF-only intake, the file has to pass through a receiver you control that enforces it. - Size: enforced. A submission is limited to 4.5 MB in total, counting every file and every other field. A larger request is rejected with HTTP 413 before Static Forms processes it, so check the total in the browser and show a readable message.
- Plan: enforced. File uploads are Starter and up. A submission with a file on the Free plan is rejected with a 400.
- Delivery and storage. Files are attached to the notification email when one is sent, and on paid plans they're stored privately and downloadable from your Inbox through short-lived links while you're signed in. The attachment storage guide covers quotas and eviction.
Because the type isn't checked, treat attachments in your inbox like any other email attachment from a stranger: open them with the same care.
Complete Working Example
This form sends a name, an email address and one PDF to Static Forms. It runs the extension, file.type and signature checks on change, keeps the input invalid while the async check runs, refuses files over 4 MB (leaving room under the 4.5 MB total for the other fields), and clears its own state on reset. Replace YOUR_API_KEY with your form's key and redirectTo with a full URL on your site.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send us a PDF</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 560px; margin: 2rem auto; padding: 0 1rem; color: #172033; }
label { display: block; font-weight: 600; margin-top: 1rem; }
input[type="text"], input[type="email"] { width: 100%; box-sizing: border-box; padding: 0.6rem; font-size: 1rem; }
input[type="file"] { margin-top: 0.5rem; }
:focus-visible { outline: 3px solid #2458d3; outline-offset: 3px; }
.hint { color: #4b5563; font-size: 0.9rem; }
.error { color: #a10e22; }
button { margin-top: 1.5rem; margin-right: 0.5rem; padding: 0.7rem 1.4rem; font-size: 1rem; }
</style>
</head>
<body>
<h1>Send us a PDF</h1>
<form id="pdf-form" action="https://api.staticforms.dev/submit" method="POST" enctype="multipart/form-data">
<input type="hidden" name="apiKey" value="YOUR_API_KEY">
<input type="hidden" name="subject" value="New PDF submission">
<input type="hidden" name="redirectTo" value="https://example.com/thank-you.html">
<label for="name">Name</label>
<input id="name" name="name" type="text" required autocomplete="name">
<label for="email">Email</label>
<input id="email" name="email" type="email" required autocomplete="email">
<label for="document">PDF document</label>
<input id="document" name="document" type="file" required
accept=".pdf,application/pdf" aria-describedby="document-hint document-error">
<p id="document-hint" class="hint">One .pdf file, up to 4 MB.</p>
<p id="document-error" class="error" aria-live="polite"></p>
<button type="submit">Send</button>
<button type="reset">Clear</button>
</form>
<script>
const form = document.getElementById('pdf-form');
const input = document.getElementById('document');
const error = document.getElementById('document-error');
const MAX_BYTES = 4 * 1024 * 1024;
const PDF_SIGNATURE = '%PDF-';
async function checkPdf(file) {
if (!file.name.toLowerCase().endsWith('.pdf')) return 'Choose a file that ends in .pdf.';
if (file.type && file.type !== 'application/pdf') return 'That file does not look like a PDF.';
if (file.size > MAX_BYTES) return 'Choose a PDF no larger than 4 MB.';
const head = new Uint8Array(await file.slice(0, PDF_SIGNATURE.length).arrayBuffer());
if (String.fromCharCode(...head) !== PDF_SIGNATURE) {
return 'That file ends in .pdf but its contents are not a PDF.';
}
return '';
}
function showError(message) {
input.setCustomValidity(message);
error.textContent = message;
if (message) input.setAttribute('aria-invalid', 'true');
else input.removeAttribute('aria-invalid');
}
async function validate() {
const file = input.files[0];
if (!file) {
showError('');
return;
}
// Stay invalid while the async check runs, so an early submit is blocked
input.setCustomValidity('Checking the file, please wait.');
showError(await checkPdf(file));
}
input.addEventListener('change', validate);
input.addEventListener('invalid', () => {
if (input.validity.valueMissing) error.textContent = 'Choose a PDF before sending.';
});
form.addEventListener('reset', () => {
showError('');
});
</script>
</body>
</html>The form submits natively, so no submit handler is needed: the browser blocks submission while the file input carries a custom validity message. The email field becomes the reply-to address on the notification, so you can answer from your inbox. The browser checks only shape the experience. Static Forms still accepts any file type, as covered above.
Test it before you rely on it:
- Submit with no file: the browser stops it and the page asks for a PDF.
- Pick a small real PDF: the error stays empty and the form submits.
- Rename a
.txtfile to.pdf: the signature check rejects it. - Pick a PDF over 4 MB: the size check rejects it.
- After an error, pick a valid PDF: the error clears and the form submits.
- Press Clear after an error, then pick a valid file: the old error doesn't come back.
Troubleshooting
| What you see | Why, and what to do |
|---|---|
| The chooser lets someone pick a non-PDF | Expected. accept is a hint, and "All files" overrides it. Check the file on change. |
| A dropped file skips your validation | Assigning input.files doesn't fire change. Call your validation right after the assignment. |
file.type is an empty string |
The browser couldn't map the extension. Fall back to the extension and signature checks instead of rejecting. |
A renamed .txt passes as .pdf |
Extension and file.type both follow the name. Add the signature check. |
| Every file stays invalid after one error | A custom validity message was never cleared. Call setCustomValidity('') before each check. |
| Valid files pass in the browser, the server rejects them | The two rule sets differ, or the whole request is over the server's size limit. Write the allowed types and limit down once and apply them in both places. |
| The page shows a hosting error after submit | The request was over 4.5 MB in total and Static Forms rejected it with 413 before it was processed. Lower the browser limit or ask for smaller files. |
FAQ
Does the accept attribute validate file types?
No. MDN says it "doesn't validate the types of the selected files; it provides hints for browsers". It filters the file chooser, and visitors can usually switch that filter to all files. Validate in JavaScript and on the server.
Can I rely on file.type to check a file's type?
Not on its own. Browsers set file.type from the file extension, it can be an empty string, and a renamed file reports its new extension's type. Combine it with an extension allowlist and a check of the file's first bytes, then check again on the server.
Why can a user upload a file that doesn't match accept?
The chooser's "All files" option overrides the filter, a script can assign any file to input.files without an accept check, and a request sent with curl never runs your page at all.
Does Static Forms check the type of uploaded files?
No. Its documentation states that the server does not enforce file type validation. It does enforce the 4.5 MB total submission size, and file uploads are Starter and up. Use accept and JavaScript checks to guide visitors, and use a receiver you control if you need a server-enforced type rule.
Next steps
Start with the file uploads docs for limits, multiple files and storage per plan, or the end-to-end HTML file upload guide if you're building the whole path from form to inbox. To try the complete example, which needs file uploads (Starter and up), create a form in the Static Forms dashboard and paste its key in place of YOUR_API_KEY.
Related Articles
Why JavaScript Can't Set a File Input's Value (and Fixes)
A file input's value can only be set to an empty string, for security. Clear it, assign files with DataTransfer, or keep your own file list and send FormData.
Preserve textarea line breaks in HTML without innerHTML
Fix textarea line breaks that disappear in a preview. Use textContent and CSS pre-wrap, keep user input as plain text, and test a complete HTML example.
Confirm email field validation in HTML and JavaScript
Build a confirm email field that catches mismatches, clears stale errors, and works with Enter. Test the exact HTML example without confusing matching with verification.









