Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

File Type Validation while Uploading it using JavaScript

  • Last Updated : 30 Jul, 2021

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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.






<!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>

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.




<!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>

Output:

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.

HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples.

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!