Validating a file size in JavaScript while uploading

File size validation is essential for web applications to prevent users from uploading files that are too large for your server or application limits. JavaScript provides built-in methods to check file size before upload begins.

How File Size Validation Works

When a user selects a file using an HTML file input, JavaScript can access the file's properties through the files property. The size property returns the file size in bytes, which we can then validate against our requirements.

Basic File Size Validation

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Size Validation</title>
    <style>
        body {
            font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        .result {
            font-size: 18px;
            font-weight: 500;
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            color: green;
            background-color: #d4edda;
        }
        .error {
            color: red;
            background-color: #f8d7da;
        }
        .file-input {
            margin: 20px 0;
            padding: 10px;
        }
    </style>
</head>
<body>
    <h1>File Size Validation Demo</h1>
    <p>Maximum file size allowed: 4 MB</p>
    
    <input type="file" class="file-input" onchange="validateFile()" />
    <div class="result" id="result"></div>
    
    <script>
        function validateFile() {
            const fileInput = document.querySelector('.file-input');
            const resultDiv = document.getElementById('result');
            
            if (fileInput.files.length === 0) {
                resultDiv.innerHTML = '';
                return;
            }
            
            const file = fileInput.files[0];
            const fileSizeInKB = Math.round(file.size / 1024);
            const fileSizeInMB = Math.round(fileSizeInKB / 1024 * 100) / 100;
            const maxSizeKB = 4096; // 4 MB in KB
            
            resultDiv.className = 'result';
            
            if (fileSizeInKB > maxSizeKB) {
                resultDiv.innerHTML = `File is too large! Size: ${fileSizeInMB} MB. Maximum allowed: 4 MB`;
                resultDiv.classList.add('error');
                fileInput.value = ''; // Clear the input
            } else {
                resultDiv.innerHTML = `File accepted! Size: ${fileSizeInMB} MB (${fileSizeInKB} KB)`;
                resultDiv.classList.add('success');
            }
        }
    </script>
</body>
</html>

Advanced Validation with Multiple Constraints

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced File Validation</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 600px;
            margin: 0 auto;
            padding: 20px;
        }
        .validation-result {
            margin: 15px 0;
            padding: 10px;
            border-radius: 4px;
        }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
    </style>
</head>
<body>
    <h1>Advanced File Validation</h1>
    <p>Allowed: Images and PDFs under 2 MB</p>
    
    <input type="file" id="fileInput" onchange="advancedValidation()" />
    <div id="validationResult"></div>
    
    <script>
        function advancedValidation() {
            const fileInput = document.getElementById('fileInput');
            const resultDiv = document.getElementById('validationResult');
            
            if (fileInput.files.length === 0) {
                resultDiv.innerHTML = '';
                return;
            }
            
            const file = fileInput.files[0];
            const maxSize = 2 * 1024 * 1024; // 2 MB in bytes
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
            
            // File size validation
            if (file.size > maxSize) {
                const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
                showResult(`File too large: ${fileSizeMB} MB. Maximum: 2 MB`, 'error');
                fileInput.value = '';
                return;
            }
            
            // File type validation
            if (!allowedTypes.includes(file.type)) {
                showResult(`Invalid file type: ${file.type}. Allowed: Images and PDFs only`, 'error');
                fileInput.value = '';
                return;
            }
            
            // Success
            const fileSizeMB = (file.size / (1024 * 1024)).toFixed(2);
            showResult(`File valid! ${file.name} (${fileSizeMB} MB)`, 'success');
        }
        
        function showResult(message, type) {
            const resultDiv = document.getElementById('validationResult');
            resultDiv.className = `validation-result ${type}`;
            resultDiv.innerHTML = message;
        }
    </script>
</body>
</html>

Key Validation Points

Property Description Usage
file.size File size in bytes Primary validation metric
file.name Original filename Display and logging
file.type MIME type File type validation

Size Conversion Helper

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];
}

// Usage examples
console.log(formatFileSize(1024));      // "1 KB"
console.log(formatFileSize(1048576));   // "1 MB"
console.log(formatFileSize(5242880));   // "5 MB"

Common Use Cases

Profile Pictures: Typically limit to 1-5 MB for images only. Document Uploads: Allow larger sizes (10-50 MB) for PDFs and office documents. Media Files: May require higher limits (100+ MB) for video content.

Conclusion

Client-side file size validation improves user experience by providing immediate feedback. Always implement server-side validation as well, since client-side validation can be bypassed. Use appropriate size limits based on your application's requirements and server capabilities.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements