Categories
JavaScript

Validate files in JavaScript easily using these 2 methods

In our last article How to easily upload files using Fetch API? we discussed how we can upload files. In this article, we are going to learn how to validate files before we upload them. In order to be totally on board, we recommend reading the previous article.

The first thing we are going to do is to create form and input type file that will enable us to upload files.

<form>
    <input type="file" name="upload" id="upload" />
</form>

Validate files using RegEx

After we have successfully done this, we are going to create our upload function, with validation. For the first case, we will use RegEx.

const uploadFunction = event => {
    const fileInput = event.target;
    const files = event.target.files
    const path = event.target.value;
    
    const allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
              
    if (!allowedExtensions.exec(path)) {
        alert('Invalid file type');
        fileInput.value = '';
        return false;
    }
  
  
    const data = new FormData()
    data.append('file', files[0])
    
    fetch('/upload-file', {
    method: 'POST',
    body: data
    })
    .then(response => response.json())
    .then(data => {
    console.log(data)
    })
    .catch(error => {
    console.error(error)
    })
}

Since we already wrote and explained fetch(), we are going to explain the validation part. We have created a variable, allowedExtensions, that holds the RegEx formula for allowed extensions. When we choose a file, its name is stored in the input‘s attribute value. So we execute RegEx against input’s value. If the file contains any of those extensions it will return true; and function will execute to the end. Hence, our file will be uploaded. But, if the extension is not in our RegEx than exec() will return false and our function will stop execution.

Validate files using split()

The second method is by using JavaScript split() method. Instead of executing RegEx against input value, we will split its value and search for the extension.

const uploadFunction = event => {
    const fileInput = event.target;
    const files = event.target.files
    const path = event.target.value;
    
    const allowedExtensions = ['jpg', 'png', 'gif'];
    
    const splitName = path.split('.');
    const extenstion = splitName[splitName.length-1];
              
    if (!allowedExtensions.include(extenstion)) {
        alert('Invalid file type');
        fileInput.value = '';
        return false;
    }
  
  
    const data = new FormData()
    data.append('file', files[0])
    
    fetch('/upload-file', {
    method: 'POST',
    body: data
    })
    .then(response => response.json())
    .then(data => {
    console.log(data)
    })
    .catch(error => {
    console.error(error)
    })
}

Let’s take a closer look at the example above. The first thing is we declare allowedExtensions variable. Then, we split value by period, ., because that is how we denote extensions. Next thing is to get the last element of the array that has been returned by split(). After that, we use includes() method to check whether that extension is included in our array allowedExtensions.

If includes() confirms that there is the extension in the array, it will return true and our function will continue. Otherwise, it will stop.

NOTE: This is neither secure nor good practice. This is just to provide our users with quick feedback before our file is sent to the server. We should always validate files both on the front end and backend.

If you have any questions or anything you can find me on my Twitter, or you can read some of my other articles like How to easily upload files using Fetch API?.