When allowing users to upload files to your site, it’s important to validate the file type and size before processing the upload — especially for security and performance reasons.
In this tutorial, you’ll learn how to check the selected file’s format (extension) and size using simple HTML and JavaScript, step by step.
👁️ Preview
🧱 Step 1: Create the File Input Field in HTML
<form id="upload-form">
<label for="file">Choose a file:</label><br><br>
<input type="file" id="file" name="file" />
<br><br>
<button type="submit">Upload</button>
</form>
<p id="message"></p>
✅ This is a basic form with:
- A file input
- A submit button
- A
<p>
tag to show validation messages
⚙️ Step 2: Add JavaScript to Validate the File
Let’s now check the file size and file type before allowing submission.
document.getElementById('upload-form').addEventListener('submit', function (e) {
const fileInput = document.getElementById('file');
const file = fileInput.files[0];
const message = document.getElementById('message');
message.textContent = '';
if (!file) {
message.textContent = 'Please select a file.';
e.preventDefault();
return;
}
// ✅ Validate file type
const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!allowedTypes.includes(file.type)) {
message.textContent = 'Only JPG, PNG, or PDF files are allowed.';
e.preventDefault();
return;
}
// ✅ Validate file size (in bytes)
const maxSize = 2 * 1024 * 1024; // 2MB
if (file.size > maxSize) {
message.textContent = 'File size must be less than 2MB.';
e.preventDefault();
}
});
✅ Explanation
file.type
: returns the MIME type, e.g."image/jpeg"
file.size
: gives the size in bytese.preventDefault()
: stops the form from submitting if validation fails
🧩 Optional: Show File Name and Size Before Upload
fileInput.addEventListener('change', function () {
const file = this.files[0];
if (file) {
message.textContent = `Selected: ${file.name} (${(file.size / 1024).toFixed(1)} KB)`;
}
});
This improves the user experience by showing basic file info before upload.
💡 Bonus: Validate by File Extension (Alternative)
If needed, you can check the extension instead of MIME type:
const allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
const fileExtension = file.name.split('.').pop().toLowerCase();
if (!allowedExtensions.includes(fileExtension)) {
message.textContent = 'Invalid file extension.';
e.preventDefault();
}
✅ Final Result
You now have a secure and user-friendly file input that:
- Validates file type (by MIME or extension)
- Validates file size before upload
- Prevents bad or oversized files from being submitted
- Gives feedback to the user in real time