File Type Validation while Uploading it using JavaScript


Social media platforms that focus solely on employment allow users to create an account and will be asked to upload the necessary documents so that the job recruiters can analyze them. To collect the documents from the user, these websites will provide an "Upload file" or "Choose file" option in their user details form; and they accept only particular file types such as ".pdf", ".jpg", ".png", etc. This process is called file validation and it can be done using JavaScript.

In this article, we are going to design an option that validates the file types using JavaScript. To do so, the following is the approach −

  • Step 1 − Create a function called validateFileType().

  • Step 2 − When the file input field value changes, trigger the validateFileType() function.

  • Step 3 − Retrieve the selected file from the file input field using document.getElementById('fileInput').files[0].

  • Step 4 − Define an array called allowedTypes that contains the allowed file types (e.g., 'image/jpeg', 'image/png', 'application/pdf').

  • Step 5 − Check if the selected file's type is included in the allowedTypes array using the includes() method.

    If the file type is found in the allowedTypes array, show the file name on the screen.

    If the file type is not found, execute the following steps.

  • Step 6 − Display an alert message to the user stating "Invalid file type. Please choose a JPEG, PNG, or PDF file."

  • Step 7 − Clear the name of the file input field by setting document.getElementById('fileInput').value to an empty string.

Example

In the following example, we are trying to validate the file types while uploading using the above approach −

<!DOCTYPE html>
<html>
<head>
   <title>File Type Validation Example</title>
   <script>
      function validateFileType() {
         var selectedFile = document.getElementById('fileInput').files[0];
         var allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];

         if (!allowedTypes.includes(selectedFile.type)) {
            alert('Invalid file type. Please upload a JPEG, PNG, or PDF file.');
            document.getElementById('fileInput').value = '';
         }
      }
   </script>
</head>
<body>
   <h1>File Type Validation Example</h1>
   <input type="file" id="fileInput" onchange="validateFileType()">
</body>
</html>

After executing the above program, try to upload a file, if the file is ".jpg", ".png", or ".pdf", it will show the file name on the screen. Else, it will show an alert stating "invalid file type".

Updated on: 04-Aug-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements