Course contentsShow
← Web Development
Lesson 2699 of 2,98248. File Uploads and HandlingFree lesson

File Extension Validation

Extract and validate file extensions from names as a secondary check alongside MIME types.

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:

  1. Get the filename from the File object's name property
  2. Extract the extension by finding the last dot and taking everything after it
  3. Normalize to lowercase (since .JPG and .jpg are the same)
  4. 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.