Is it possible to validate the size and type of input=file in HTML5?

Yes, it is possible to validate the size and type of input type="file" in HTML5. You can achieve this using JavaScript to access the File API and check file properties before form submission.

HTML5 File Validation Structure

The HTML5 File API provides access to file properties like size, type, and name through the files property of the input element.

<!DOCTYPE html>
<html>
<head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
   <form id="fileForm">
      <input type="file" id="myfile" data-max-size="1048576" accept=".jpg,.png,.pdf" />
      <input type="submit" value="Upload File"/>
   </form>
   <div id="message"></div>
   
   <script>
      $(document).ready(function(){
         $('#fileForm').submit(function(e){
            e.preventDefault();
            
            var fileInput = $('#myfile')[0];
            var file = fileInput.files[0];
            
            if (!file) {
               $('#message').text('Please select a file.');
               return false;
            }
            
            // Validate file size (1MB = 1048576 bytes)
            var maxSize = parseInt($(fileInput).attr('data-max-size'), 10);
            if (file.size > maxSize) {
               $('#message').text('File size exceeds 1MB limit.');
               return false;
            }
            
            // Validate file type
            var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            if (!allowedTypes.includes(file.type)) {
               $('#message').text('Invalid file type. Only JPG, PNG, and PDF allowed.');
               return false;
            }
            
            $('#message').text('File is valid: ' + file.name + ' (' + file.size + ' bytes)');
         });
      });
   </script>
</body>
</html>

Pure JavaScript Validation

You can also implement file validation without jQuery using vanilla JavaScript:

<!DOCTYPE html>
<html>
<body>
   <form id="uploadForm">
      <input type="file" id="fileInput" />
      <button type="submit">Validate & Upload</button>
   </form>
   <div id="result"></div>
   
   <script>
      document.getElementById('uploadForm').addEventListener('submit', function(e) {
         e.preventDefault();
         
         const fileInput = document.getElementById('fileInput');
         const file = fileInput.files[0];
         const resultDiv = document.getElementById('result');
         
         if (!file) {
            resultDiv.innerHTML = '<span style="color: red;">No file selected</span>';
            return;
         }
         
         // Check file size (limit: 2MB)
         const maxSize = 2 * 1024 * 1024; // 2MB in bytes
         if (file.size > maxSize) {
            resultDiv.innerHTML = '<span style="color: red;">File too large: ' + 
                                 (file.size / 1024 / 1024).toFixed(2) + 'MB</span>';
            return;
         }
         
         // Check file type
         const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
         if (!allowedTypes.includes(file.type)) {
            resultDiv.innerHTML = '<span style="color: red;">Invalid type: ' + 
                                 file.type + '</span>';
            return;
         }
         
         resultDiv.innerHTML = '<span style="color: green;">Valid file: ' + 
                              file.name + ' (' + file.type + ')</span>';
      });
   </script>
</body>
</html>

File Properties Available

The HTML5 File API provides access to these file properties:

Property Description Example
file.name Original filename "document.pdf"
file.size File size in bytes 1048576
file.type MIME type "application/pdf"
file.lastModified Last modified timestamp 1640995200000

Common Validation Patterns

Here are typical validation scenarios:

function validateFile(file) {
   // Size validation (5MB limit)
   if (file.size > 5 * 1024 * 1024) {
      return 'File must be less than 5MB';
   }
   
   // Type validation for images
   const imageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
   if (!imageTypes.includes(file.type)) {
      return 'Only image files (JPG, PNG, GIF, WebP) are allowed';
   }
   
   // Extension validation (additional security)
   const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
   const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
   if (!allowedExtensions.includes(fileExtension)) {
      return 'Invalid file extension';
   }
   
   return null; // Valid file
}

Conclusion

HTML5 File API enables comprehensive client-side validation of file size, type, and other properties. Always combine client-side validation with server-side checks for security.

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

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements