Skip to content

How to Validate Media Uploads in JavaScript

Validation has become an essential concept in software development and the security of an application. We often run tests for vulnerability using validation on input fields. There are different types of validation in software development; this tutorial will focus on media files, validating the file extension, the number of files to be uploaded, and the file size.

We will be using the live-server dependency for our development to aid with live-reload capability. Run the command below to install the dependency globally.

npm install -g live-server

Navigate to the project folder and create an index.html file. paste the code below in the index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Validate File Uploads</title>
    <script src="https://cdn.tailwindcss.com"></script>
  </head>
<body>
  <main class="flex justify-center h-screen items-center">
    <div class="flex flex-col justify-center">
      <input class="hidden" type="file" multiple name="filePicker" />
        <p class="text-red-500 mb-4" id="error"></p>
        <p class="text-green-500 mb-4" id="success"></p>
        <div class="grid place-items-center">
          <button class="text-white bg-gray-700 hover:bg-gray-600 px-6 py-2 rounded">
            Upload
          </button>
        </div>
    </div>
  </main>
<script src="./index.js"></script>
</body>
</html>
Code language: HTML, XML (xml)

Create an index.js file at the root of the project and paste the code below.

const videoMimeTypes = [
  'video/x-flv',
  'video/x-ms-wmv',
  'video/x-msvideo',
  'video/quicktime',
  'video/3gpp',
  'video/MP2T',
  'application/x-mpegURL',
  'video/mp4',
];

const imageMimeTypes = [
  'image/webp',
  'image/tiff',
  'image/svg+xml',
  'image/png',
  'image/jpeg',
  'image/vnd.microsoft.icon',
  'image/gif',
  'image/bmp',
];
Code language: JavaScript (javascript)

The code above are the mime types where we add our extension types for images and videos. These types are the list of allowed types that can be uploaded.

Before writing our validation functions, create an onload function to confirm that the page is done loading before running the javascript code.

window.onload = function validation() {
  //our code will be here
}
Code language: JavaScript (javascript)

Our codes will be nested within the onload function.

Create javascript variables to point to the HTML tags using the querySelector. Paste the code below inside the onload function.

const filePicker = document.querySelector('input');
const button = document.querySelector('button');
const errorParagraph = document.querySelector('#error');
const successParagraph = document.querySelector('#success');
Code language: JavaScript (javascript)

Next is to implement an onClick on the upload button. The function below will execute once we click on the upload button. It triggers the filePicker function, which is attached to a change listener. The change event is triggered when we upload a file.

button.addEventListener('click', () => {
  if (filePicker) filePicker.click();
});
    
filePicker.addEventListener('change', (e) => {
  const files = e.target.files;
  console.log(files);
    
// validation functions here 
    
});
Code language: PHP (php)

Once we drop the file in the browser, we need to start validating it. Here are the function signature of the validation we need to write:

function validateSize(file, max)
function validateExtension(file, allowedExtensions = [])
function validateLength(files, max)
function updateErrorMessage(el, message)
function updateSuccessMessage(el, message)
Code language: JavaScript (javascript)

Each of these functions has a vital role in validating our file upload.

  • validateSize: handles the uploaded file size.
  • validateExtension: handles the file extension of the uploaded file as listed in our mime types.
  • validateLength: handles the number of files we can upload at once.

We will be showing the code behind each of these functions as we go further. We will first start with the validateSize function, which validates the size of our file in Megabyte.

function validateSize(file, max) {
  return file.size <= max;
}
Code language: JavaScript (javascript)

Next is the validateExtension funtion**,** which ****validates the type of extensions allowed.

function validateExtension(file, allowedExtensions = []) {
  return allowedExtensions.includes(file.type);
}
Code language: JavaScript (javascript)

Next is the validateLength, which validates that the total number of files uploaded at once is valid.

function validateLength(file, max){
  return file.length <= max;
}
Code language: JavaScript (javascript)

We can also have a few functions to display our error and success messages.

function updateErrorMessage(el, message) {
  el.innerText = message;
  console.warn(message);
}
function updateSuccessMessage(el, message) {
  el.innerText = message;
  console.log(message);
}
Code language: JavaScript (javascript)

Now that we have defined our validation, error, and success function, we will head back to the filepicker change handle to start our conditions for validation using the functions. We will start by validating only length. To validate only the length paste the code below in the change listener.

if (!validateLength(files, 3)) {
  updateErrorMessage(errorParagraph, 'Number of files must not exceed 3.');
} else {
  updateSuccessMessage(successParagraph, 'All files passed validation!');
}
Code language: JavaScript (javascript)

To validate length and extensions of our files paste the code below.

if (!validateLength(files, 3)) {
  updateErrorMessage(errorParagraph, 'Number of files must not exceed 3.');
} else {
  for (f of files) {
    if (!validateExtension(f, [...imageMimeTypes, ...videoMimeTypes])) {
      updateErrorMessage(
        errorParagraph,
        `${f.name} is neither an image or a video.`
      );
      break;
    }
    updateSuccessMessage(successParagraph, 'All files passed validation!');
  }
}
Code language: JavaScript (javascript)

To validate the size, length, and extension of every uploaded file, paste the code below.

if (!validateLength(files, 3)) {
  updateErrorMessage(errorParagraph, 'Number of files must not exceed 3.');
} else {
  for (f of files) {
    if (!validateExtension(f, [...imageMimeTypes, ...videoMimeTypes])) {
      updateErrorMessage(
      errorParagraph,
      `${f.name} is neither an image or a video.`
      );
      break;
    }
    if (!validateSize(f, 1024 ** 2 * 2)) {
      updateErrorMessage(
      errorParagraph,
      `${f.name}'s size exceeds 2 Megabytes`
      );
      break;
    }
    updateSuccessMessage(successParagraph, 'All files passed validation!');
  }
}
Code language: JavaScript (javascript)

In this tutorial, we have discussed and shown how easy it is to validate media files making it easier to protect our applications from unwanted and irrelevant files that may disrupt the performance of our application. The complete source code for this tutorial is available on CodeSandbox.

Back to top

Featured Post