Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
File Type Validation while Uploading it using JavaScript
File type validation is essential for web applications that handle file uploads. It ensures users only upload acceptable file formats, preventing security issues and maintaining data consistency. JavaScript provides built-in properties to check file types before submission.
This validation process helps platforms like job portals, social media sites, and document management systems control what file types users can upload, such as restricting uploads to PDFs for resumes or images for profile pictures.
How File Type Validation Works
When a user selects a file, the browser exposes file information through the File API. The key property is file.type, which returns the MIME type (e.g., 'image/jpeg', 'application/pdf'). We compare this against an array of allowed types.
Basic File Validation Example
Here's a complete example that validates file types and provides user feedback:
<!DOCTYPE html>
<html>
<head>
<title>File Type Validation</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.file-info { margin-top: 15px; padding: 10px; border-radius: 4px; }
.success { background-color: #d4edda; border: 1px solid #c3e6cb; color: #155724; }
.error { background-color: #f8d7da; border: 1px solid #f5c6cb; color: #721c24; }
input[type="file"] { margin: 10px 0; }
</style>
</head>
<body>
<h1>File Type Validation Example</h1>
<p>Please select a JPEG, PNG, or PDF file:</p>
<input type="file" id="fileInput" onchange="validateFileType()">
<div id="fileInfo"></div>
<script>
function validateFileType() {
var fileInput = document.getElementById('fileInput');
var fileInfo = document.getElementById('fileInfo');
var selectedFile = fileInput.files[0];
// Clear previous messages
fileInfo.innerHTML = '';
if (!selectedFile) {
return;
}
var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
var fileSize = (selectedFile.size / 1024 / 1024).toFixed(2); // Size in MB
if (allowedTypes.includes(selectedFile.type)) {
fileInfo.innerHTML = '<div class="file-info success">' +
'<strong>? Valid file selected:</strong><br>' +
'Name: ' + selectedFile.name + '<br>' +
'Type: ' + selectedFile.type + '<br>' +
'Size: ' + fileSize + ' MB' +
'</div>';
} else {
fileInfo.innerHTML = '<div class="file-info error">' +
'<strong>? Invalid file type!</strong><br>' +
'Please select a JPEG, PNG, or PDF file.' +
'</div>';
fileInput.value = ''; // Clear the input
}
}
</script>
</body>
</html>
Advanced Validation with File Size Check
Often you'll want to combine file type validation with file size limits:
<!DOCTYPE html>
<html>
<head>
<title>Advanced File Validation</title>
</head>
<body>
<h1>Advanced File Validation</h1>
<input type="file" id="advancedFileInput" onchange="advancedValidation()">
<div id="validationResult"></div>
<script>
function advancedValidation() {
var fileInput = document.getElementById('advancedFileInput');
var result = document.getElementById('validationResult');
var file = fileInput.files[0];
if (!file) return;
var allowedTypes = {
'image/jpeg': { maxSize: 5, name: 'JPEG' },
'image/png': { maxSize: 5, name: 'PNG' },
'application/pdf': { maxSize: 10, name: 'PDF' }
};
var fileSizeMB = file.size / 1024 / 1024;
if (!allowedTypes[file.type]) {
result.innerHTML = '<p style="color: red;">Invalid file type. Only JPEG, PNG, and PDF files are allowed.</p>';
fileInput.value = '';
return;
}
if (fileSizeMB > allowedTypes[file.type].maxSize) {
result.innerHTML = '<p style="color: red;">File too large. ' +
allowedTypes[file.type].name + ' files must be under ' +
allowedTypes[file.type].maxSize + 'MB.</p>';
fileInput.value = '';
return;
}
result.innerHTML = '<p style="color: green;">? File validated successfully: ' +
file.name + ' (' + fileSizeMB.toFixed(2) + ' MB)</p>';
}
</script>
</body>
</html>
Multiple File Validation
For handling multiple file uploads with validation:
<!DOCTYPE html>
<html>
<head>
<title>Multiple File Validation</title>
</head>
<body>
<h1>Multiple File Validation</h1>
<input type="file" id="multipleFiles" multiple onchange="validateMultipleFiles()">
<div id="multipleResults"></div>
<script>
function validateMultipleFiles() {
var fileInput = document.getElementById('multipleFiles');
var results = document.getElementById('multipleResults');
var files = Array.from(fileInput.files);
var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
var validFiles = [];
var invalidFiles = [];
files.forEach(function(file) {
if (allowedTypes.includes(file.type)) {
validFiles.push(file.name);
} else {
invalidFiles.push(file.name);
}
});
var output = '<h3>Validation Results:</h3>';
if (validFiles.length > 0) {
output += '<p style="color: green;"><strong>Valid files (' + validFiles.length + '):</strong><br>' +
validFiles.join('<br>') + '</p>';
}
if (invalidFiles.length > 0) {
output += '<p style="color: red;"><strong>Invalid files (' + invalidFiles.length + '):</strong><br>' +
invalidFiles.join('<br>') + '</p>';
}
results.innerHTML = output;
}
</script>
</body>
</html>
Common MIME Types
| File Extension | MIME Type | Description |
|---|---|---|
| .jpg, .jpeg | image/jpeg | JPEG Image |
| .png | image/png | PNG Image |
| application/pdf | PDF Document | |
| .doc | application/msword | Word Document |
| .docx | application/vnd.openxmlformats-officedocument.wordprocessingml.document | Word Document (newer) |
Key Points
Client-side validation: JavaScript validation improves user experience but should be combined with server-side validation for security
File.type property: Returns the MIME type, which is more reliable than checking file extensions
User feedback: Always provide clear feedback about why a file was rejected
Reset input: Clear the file input when validation fails to prevent form submission with invalid files
Conclusion
File type validation in JavaScript is straightforward using the File API's type property and the includes() method. Combine it with file size checks and clear user feedback for a complete validation solution that enhances both user experience and application security.
