File Extension Validation
You'll learn how to extract and validate file extensions as a defensive secondary check beyond MIME type validation.
Why Extension Validation Matters
While MIME type validation (which you just learned) is crucial, relying on it alone isn't foolproof. Users can rename files, and browsers sometimes misidentify MIME types. Validating the file extension provides an additional layer of security—think of it as requiring both a passport and a driver's license instead of just one form of ID.
How to Extract and Validate Extensions
File extensions are extracted from the filename string. You'll typically:
- Get the filename from the File object's
nameproperty - Extract the extension by finding the last dot and taking everything after it
- Normalize to lowercase (since
.JPGand.jpgare the same) - Check against an allowlist of permitted extensions
Here's the pattern:
const file = fileInput.files[0];
const fileName = file.name;
const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
const allowedExtensions = ['jpg', 'jpeg', 'png', 'gif'];
if (!allowedExtensions.includes(extension)) {
console.error('Invalid file extension');
}
Combining with MIME Type Validation
Extension validation should complement, not replace, MIME type checking. Validate both:
const isValidMIME = ['image/jpeg', 'image/png'].includes(file.type);
const isValidExtension = ['jpg', 'jpeg', 'png'].includes(extension);
if (isValidMIME && isValidExtension) {
// Proceed with upload
}
Key Takeaway: File extension validation adds a secondary security layer by checking the filename suffix, but always use it alongside MIME type validation—never as a standalone defense.