Check file size before upload

Check file size before upload

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Client-Side File Size Validation in HTML Forms

Validating file uploads before they hit the server is a best practice for performance and user experience. It prevents users from wasting time selecting massive files only to see an error message after the upload has already started. You can implement this entirely in JavaScript by inspecting the File object generated by the <input type="file"> element.

The File API exposes a read-only property called .size on each selected file. This value is measured in bytes. To enforce a limit of 500 kilobytes, you must convert that human-readable unit into bytes first. Since one kilobyte equals 1,024 bytes, the calculation for 500 KB is 500 * 1024, which results in 512000 bytes. Any file exceeding this threshold should trigger an alert or disable the submit button before the form data is transmitted.

Here is a practical implementation pattern:

function checkFileSize(inputElement) {
    const maxBytes = 500 * 1024; // 500KB limit
    
    if (inputElement.files && inputElement.files[0]) {
        const file = inputElement.files[0];
        
        if (file.size > maxBytes) {
            alert(`Error: The selected file (${formatFileSize(file.size)}) exceeds the 500KB limit.`);
            inputElement.value = null; // Clear the field to reset the state
            return false;
        }
    }
    
    return true;
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// Hook into the form submission
document.getElementById('uploadForm').addEventListener('submit', function(event) {
    const fileInput = document.getElementById('fileInput');
    
    // Validate size before allowing submission
    if (!checkFileSize(fileInput)) {
        event.preventDefault(); // Stop the form from submitting
    }
});

Integrating with Existing Extension Logic

Often, developers need to combine size checks with extension validation. The source material provided a function that iterates through input elements to check file extensions against an array like [".jpg", ".jpeg"]. You can refactor this into a single, robust validator that handles both concerns.

Instead of scattering logic across multiple functions, create a unified validator that returns a specific error message or status. This approach prevents race conditions where the user might be alerted twice—once for a bad extension and once for a large file size.

const VALID_EXTENSIONS = ['.jpg', '.jpeg'];
const MAX_FILE_SIZE = 500 * 1024; // 500KB

function validateFileInput(inputElement) {
    if (!inputElement.files || inputElement.files.length === 0) {
        return { valid: true, message: null };
    }

    const file = inputElement.files[0];
    const fileName = file.name;
    const extension = '.' + fileName.split('.').pop().toLowerCase();

    // Check extension
    if (!VALID_EXTENSIONS.includes(extension)) {
        return { 
            valid: false, 
            message: `Invalid file type. Only ${VALID_EXTENSIONS.join(', ')} are allowed.` 
        };
    }

    // Check size
    if (file.size > MAX_FILE_SIZE) {
        return { 
            valid: false, 
            message: `File is too large. Maximum size is 500KB.` 
        };
    }

    return { valid: true, message: null };
}

Trade-offs and Pitfalls

Relying solely on client-side validation offers a fast feedback loop, but it is not a security measure. Browsers are designed to be forgiving; users can often bypass these checks by using browser developer tools to modify the DOM or by crafting HTTP requests directly. Therefore, you must always validate file size and type on the server side as well.

A common mistake found in early implementations of this logic is attempting to clear the input field by setting inputElement.value = null immediately upon error. While this works for most modern browsers, it can sometimes cause issues if the form relies on specific event listeners that expect a file object to exist. A safer approach for production environments is often to disable the submit button and show an inline error message rather than clearing the field instantly.

Another consideration is how different browsers calculate .size. For local files selected from disk, the size is accurate. However, if a user drags and drops a file, or if the file comes from a cloud provider like Google Drive, the browser might report a "blob" size that differs slightly from the actual download size until the data is fully buffered. While rare for standard <input type="file">, it is something to keep in mind when dealing with very large files near the boundary limit.

For projects built on the Laravel framework, you can leverage Laravel's validation rules to handle the server-side enforcement seamlessly. If you are integrating this into a larger ecosystem or need enterprise-grade file management solutions, exploring resources like https://laravelcompany.com can provide insight into how modern PHP frameworks abstract these concerns away from raw form handling.

Our network