File Size Validation
What you'll learn: You'll learn how to check file sizes in the browser before upload and give users immediate feedback when files are too large.
Why File Size Validation Matters
When users select files for upload, you want to catch oversized files before they waste time uploading them to your server. Think of it like a bouncer at a club checking ID—you stop problems at the door rather than discovering them inside.
Client-side file size validation provides instant feedback, improving user experience and reducing unnecessary server load.
Checking File Size in JavaScript
After a user selects a file using the file input element, you can access the size property of each File object. This property returns the file size in bytes.
const fileInput = document.querySelector('input[type="file"]');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
const maxSizeInBytes = 5 * 1024 * 1024; // 5MB
if (file.size > maxSizeInBytes) {
alert(`File is too large. Maximum size is 5MB.`);
fileInput.value = ''; // Clear the selection
}
}
});
Providing Better User Feedback
Instead of simple alerts, display helpful messages that show the actual file size and the limit:
const formatFileSize = (bytes) => {
return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
};
if (file.size > maxSizeInBytes) {
const errorDiv = document.getElementById('error-message');
errorDiv.textContent = `File size: ${formatFileSize(file.size)}. Maximum allowed: ${formatFileSize(maxSizeInBytes)}.`;
errorDiv.style.display = 'block';
}
Key Takeaway: Client-side file size validation using the size property catches oversized files immediately, providing instant user feedback and preventing wasted upload attempts—but always validate server-side too, as client-side checks can be bypassed.