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

Validation State Management

Track validation status per file to enable/disable upload buttons and show progress.

Validation State Management

You'll learn how to track each file's validation status so you can intelligently control UI elements like upload buttons and progress indicators.

The Core Idea

When users select or drop multiple files, each file may pass or fail different validation checks (size, type, dimensions). Validation state management means maintaining a data structure that tracks which files are valid, which are invalid, and why. This state lets you make smart decisions: disable the upload button if any file fails, show per-file error messages, or display a count of files ready to upload.

Think of it like a quality control station: each item (file) gets a pass/fail sticker, and you only allow the batch to proceed when all items meet standards—or you clearly mark which ones don't.

Tracking Validation Status

Create an object or array to store validation results for each file:

const fileStates = new Map();

function validateAndTrack(file) {
  const errors = [];
  
  if (file.size > 5 * 1024 * 1024) {
    errors.push('File exceeds 5MB');
  }
  
  if (!file.type.startsWith('image/')) {
    errors.push('Must be an image');
  }
  
  fileStates.set(file.name, {
    file: file,
    isValid: errors.length === 0,
    errors: errors
  });
}

function canUpload() {
  for (let state of fileStates.values()) {
    if (!state.isValid) return false;
  }
  return fileStates.size > 0;
}

const uploadButton = document.getElementById('uploadBtn');
uploadButton.disabled = !canUpload();

By checking canUpload() after every validation, you enable the upload button only when all files are valid. You can also iterate through fileStates to display specific error messages next to each file preview.

Key Takeaway:
Validation state management tracks each file's validity in a data structure, enabling dynamic UI updates that reflect overall upload readiness and per-file feedback.