File Type Validation while Uploading it using JavaScript

In this article, we will learn how to implement file type validation by checking file extension before uploading it using Javascript. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time.

Using JavaScript, you can easily check the selected file extension with allowed file extensions and can restrict the user to upload only the allowed file types. For this we will use fileValidation() function. We will create fileValidation() function that contains the complete file type validation code. In this function we will use regex to check the type of file by the given pattern.

Below examples implement the above approach:

Example 1: In this example we upload file having extensions .jpeg/.jpg/.png/.gif only. We store an extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use regular expression and also preview the uploaded file if the uploaded file extension follows the file type.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        File Type Validation while
        Uploading it using JavaScript
    </title>
  
    <style>
        h1 {
            color: green;
        }
          
        body {
            text-align: center;
        }
    </style>
</head>
  
<body>
    <h1
        GeeksforGeeks 
    </h1>
  
    <h3
        Validation of file type while 
        uploading using JavaScript? 
    </h3>
  
    <!-- File input field -->
    <p>Upload an Image</p>
    <input type="file" id="file"
        onchange="return fileValidation()" />
  
    <!-- Image preview -->
    <div id="imagePreview"></div>
    <script>
        function fileValidation() {
            var fileInput = 
                document.getElementById('file');
              
            var filePath = fileInput.value;
          
            // Allowing file type
            var allowedExtensions = 
                    /(\.jpg|\.jpeg|\.png|\.gif)$/i;
              
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type');
                fileInput.value = '';
                return false;
            
            else 
            {
              
                // Image preview
                if (fileInput.files && fileInput.files[0]) {
                    var reader = new FileReader();
                    reader.onload = function(e) {
                        document.getElementById(
                            'imagePreview').innerHTML = 
                            '<img src="' + e.target.result
                            + '"/>';
                    };
                      
                    reader.readAsDataURL(fileInput.files[0]);
                }
            }
        }
    </script>
</body>
  
</html>

chevron_right


Output:



Example 2: Uploading the file having extensions .doc/.docx/.odt/.pdf/.tex/.txt/.rtf/.wps/.wks/.wpd only. Store the extension list in a variable and compare each of them with the uploaded file extension. To separate the extension from the uploaded file we will use a regular expression.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        File Type Validation while
        Uploading it using JavaScript
    </title>
  
    <style>
        h1 {
            color: green;
        }
          
        body {
            text-align: center;
        }
    </style>
</head>
  
<body>
    <h1
        GeeksforGeeks 
    </h1>
  
    <h3
        Validation of file type while 
        uploading using JavaScript? 
    </h3>
  
    <!-- File input field -->
    <p>Upload an Image</p>
    <input type="file" id="file"
        onchange="return fileValidation()" />
  
    <!-- Image preview -->
    <div id="imagePreview"></div>
    <script>
        function fileValidation() {
            var fileInput = 
                document.getElementById('file');
              
            var filePath = fileInput.value;
          
            // Allowing file type
            var allowedExtensions = 
/(\.doc|\.docx|\.odt|\.pdf|\.tex|\.txt|\.rtf|\.wps|\.wks|\.wpd)$/i;
              
            if (!allowedExtensions.exec(filePath)) {
                alert('Invalid file type');
                fileInput.value = '';
                return false;
            
        }
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Small things always make you to think big

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.