File upload validations in javascript
Published: 2022-02-17 08:27:36

In the web application, from the security point of view file validation is the most important parameter that needs to be considered by each developer especially when doing the file upload. The validations can be either client-side or server-side or maybe both.

This article shows you how could you validate the File Type (Extension) and File Size before uploading it to the server. This demonstration will be shown for the client-side validation using javascript.


## File Type (Extension) Validation
Using Javascript, we could easily validate the file type by extracting the file extension with the allowed file types.

## Example of File Type Validation
Below is the sample example for the file type validation. In this example, we upload files having extensions .jpeg/.jpg/.png/.gif only. We are going to define a javascript function validateFileType() that will be called on the upload button click.

```
<!DOCTYPE html>
<html>  
<head>
    <title>
        File type validation while uploading using JavaScript
    </title>
    <style>
        body{
            text-align:center;
        }
    </style>
</head>  
<body>  
    <h1>File type validation while uploading using JavaScript</h1>  
    <p>Upload an image (.jpg,.jpeg,.png,.gif)</p>
 
    <!-- input element to choose a file for uploading -->
    <input type="file" id="file-upload" />
    <br><br>
 
    <!-- button element to validate file type on click event -->
    <button onclick="validateFileType()">Upload</button>
      
    <script>
 
    /* javascript function to validate file type */
    function validateFileType() {
        var inputElement = document.getElementById('file-upload');
        var files = inputElement.files;
        if(files.length==0){
            alert("Please choose a file first...");
            return false;
        }else{
            var filename = files[0].name;
 
            /* getting file extenstion eg- .jpg,.png, etc */
            var extension = filename.substr(filename.lastIndexOf("."));
 
            /* define allowed file types */
            var allowedExtensionsRegx = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
 
            /* testing extension with regular expression */
            var isAllowed = allowedExtensionsRegx.test(extension);
 
            if(isAllowed){
                alert("File type is valid for the upload");
                /* file upload logic goes here... */
            }else{
                alert("Invalid File Type.");
                return false;
            }
        }
    }
    </script>
</body>  
</html>
```


Let’s understand the above code implementation with sample points:

- An HTML <input> element is defined with attribute type=”file” to choose a file for uploading.
- An HTML <button> element is defined to call the validateFileType() function on click event to validate file type before uploading.
- Inside validateFileType(), getting inputElement by calling javascript function getElementById().
- Using inputElement.files, getting the files object.
- Using files.length, checking wether user has chosen any file or not.
- Using files[0].name, getting the name of the file with extension (eg- wallpager.png).
- Defining regular expression allowedExtensionsRegx variable with allowed file types(.JPG, .JPEG, .PNG, .GIF only).
- Using the test() function, checking wether the file type is allowed or not. It returns boolean value true or false.

## Preview

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ibp136pn8y2n3i1u5ifi.png)

Learn more: [https://javacodepoint.com/file-upload-validations-in-javascript/](https://javacodepoint.com/file-upload-validations-in-javascript/)