File Type Validation while Uploading it using JavaScript - GeeksforGeeks

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.
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.
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Create a Responsive Navbar using ReactJS
Design a web page using HTML and CSS
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction)