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

Displaying Validation Errors

Show clear, actionable error messages for failed validations inline with file inputs.

Displaying Validation Errors

What you'll learn: How to present clear, inline error messages when uploaded files fail validation checks.

After validating file size, type, extension, dimensions, or counts, you need to communicate failures to your users. Displaying errors right next to the file input—rather than hiding them in console logs or generic alerts—creates a smooth, professional experience.

Why Inline Error Display Matters

Think of validation errors like a helpful librarian pointing at a shelf: "That book doesn't belong here." Generic alerts are like shouting from across the library—everyone hears, but no one knows which book is wrong. Inline messages place the feedback exactly where the problem occurred.

Creating Error Display Elements

Add a dedicated container near your file input:

<input type="file" id="avatar" accept="image/*">
<div id="avatar-error" class="error-message" style="color: red; display: none;"></div>

Showing Validation Errors

When validation fails, populate and reveal the error element:

const fileInput = document.getElementById('avatar');
const errorDiv = document.getElementById('avatar-error');

fileInput.addEventListener('change', (e) => {
  const file = e.target.files[0];
  
  if (file.size > 2 * 1024 * 1024) {
    errorDiv.textContent = 'File must be smaller than 2MB';
    errorDiv.style.display = 'block';
    fileInput.value = ''; // Clear invalid file
    return;
  }
  
  // Clear any previous errors on success
  errorDiv.style.display = 'none';
  errorDiv.textContent = '';
});

Clear and Actionable Messages

Tell users what went wrong and how to fix it:

  • ❌ "Invalid file"
  • ✅ "File must be smaller than 2MB. Selected file: 3.5MB"

Key Takeaway: Display validation errors inline with specific, actionable messages that guide users toward successful uploads.