Filtering and validating file uploads with Javascript
Tags: javascript, validation
Published: 2020-11-07 13:50:04

---
title: Filtering and validating file uploads with Javascript
published: true
description: client-side validation of files
tags: #javascript #validation
cover_image: https://cdn.pixabay.com/photo/2014/12/29/17/39/code-583073_960_720.jpg
---
I was working on the backend (using PHP and MySQL) of a personal project where I had to validate and filter files, allowing only png, and files below a certain size on the server. 

I did the validation and filtering on the back end before realizing I could do the same on the frontend. This gives double-layered protection. Well, validation on the front end could be bypassed easily, but at least, it contributes to the robustness.

Here are the ways to achieve this on the front end using HTML or javascript.

## Using just HTML

With HTML, you have to specify the file types using the **accept** attribute. With this, the window that appears after clicking the file upload button will display only those files specified in the **accept** attribute.

```html
<input type="file" multiple accept=".jpg, .png"/>
```

In the above example, I am *accepting* only **jpg** and **png** files. Other files types like **pdf** or **docx** won't even show in the selection window. 

This method is not really robust as the user could click **All files** from the file selection window, which would then display all file types for him to choose from (including the files we are trying to avoid)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/4ts3db5nspmzbs8lwmww.PNG)


Notice I have also included **multiple** to allow for multiple file uploads. 


Moreover, you have no control over the size of the files. This is where Javascript comes in.

## Using javascript

With javascript, we have control over the type of file as well as the size and other metadata the file comes with. The whole idea behind this procedure revolves around the **file object** that is created when we upload a file. This file object contains information about the file such as its name, size, date modified or created etc.

```javascript

//attaching "change" event to the file upload button
document.getElementById("file").addEventListener("change", validateFile)

function validateFile(){
  const allowedExtensions =  ['jpg','png'],
        sizeLimit = 1_000_000; // 1 megabyte
  
  // destructuring file name and size from file object
  const { name:fileName, size:fileSize } = this.files[0];
  
  /*
  * if filename is apple.png, we split the string to get ["apple","png"]
  * then apply the pop() method to return the file extension
  *
  */
  const fileExtension = fileName.split(".").pop();
  
  /* 
    check if the extension of the uploaded file is included 
    in our array of allowed file extensions
  */
  if(!allowedExtensions.includes(fileExtension)){
    alert("file type not allowed");
    this.value = null;
  }else if(fileSize > sizeLimit){
    alert("file size too large")
    this.value = null;
  }
}

```

{% codepen https://codepen.io/wizardofcodez/pen/abNwMXR %}

**Are the better ways to do this? Or are my explanations confusing? How could I improve them. Let me know in the comments. Thanks for reading**