File Extension/Type Validation in JavaScript Before Upload

Robin
Updated on October 8, 2022

Whenever we accept files from our users, we perform file extension validation or file type validation in JavaScript. In this way, a website can restrict a user to upload certain types of files.

First access the selected file from the input field to perform file extension or type validation in JavaScript. Extract the extension from that file using split() and pop() methods then check if it matches the allowed file extensions on the website.

There are many file validation techniques in JavaScript that you should follow to make your website more secure. That's why it is very important for us when we handle files.

You can also provide a better user experience by showing an appropriate error message if someone tries to upload the wrong type of file.

In this article, I will show how you can check file extensions in JavaScript before uploading to the server.

Validate File Extension or Type in JavaScript Before Upload

I will run the validation whenever a user selects a file using the HTML <input> tag. By default, this tag accepts text. But you need to set the type="file" to take a file as its value.

There are 2 steps to validate file extension or type in JavaScript:

  1. Get the file extension from the filename with JavaScript.
  2. Check the uploaded file extension if it matches the allowed extensions.

Let's go through each step in detail with examples.

Step 1: Get The File Extension with JavaScript

There are many ways to get file extensions using JavaScript from a filename. In this case, I will listen to the change event on the input field and extract the filename from the event object.

          <form>
    <input type="file" name="profile" id="profile">
    <button id="btn">Submit</button>
</form>
        

I have a <input> field with an id profile inside a form. I will use the change event on this field to extract the filename.

          const profile = document.getElementById('profile');

profile.addEventListener('change', (event) => {
    const filename = event.target.files[0].name;

    const extension = filename.split('.').pop();
    
    console.log(extension);
    // jpg
});

        

As you can see, I am using the change event and getting the filename from the target property in the event object.

Then I will get the extension of that file with the split() and pop() methods in JavaScript. If a user selects a file image.jpg in this field, I will get jpg as the extension value. It doesn't include the dot (.) in the extension name.

When we get the extension from the uploaded file, this step completes. Now, we will move to the next step.

Also Read: Input VS Change VS Blur VS Focus - Differences of JavaScript Events

Step 2: Check The Uploaded File Extension

In this step, I will match the file extension with the list of allowed extensions. I have an array where I have listed some file types that our website will accept for this input field.

We will only upload the selected file if it matches those file types. Otherwise, we can handle it as an error and display a message to our users.

They will understand the problem and choose the correct type of file. That's how we can improve the user experience on our website.

          const extension = filename.split('.').pop();

const allowedExtensions = ['jpg', 'jpeg', 'png'];

if (allowedExtensions.includes(extension)) {
    // Upload file to the server

} else {
    // Handle error
    alert(`Please upload ${allowedExtensions.join(', ')} files`);
}
        

I am using the includes() method to check whether the allowedExtensions array contains the selected file extension or not.

If the array contains the extension that means the selected file is allowed to upload. Now you can upload it to the server or perform other validation checks.

If the array doesn't contain the extension that means it is not allowed on our website for this <input> field. Now you can display the message to the user inside the else block.

This is the complete JavaScript code you need to write to check the file type:

          const profile = document.getElementById('profile');

profile.addEventListener('change', (event) => {
    const filename = event.target.files[0].name;

    const extension = filename.split('.').pop();

    const allowedExtensions = ['jpg', 'jpeg', 'png'];

    if (allowedExtensions.includes(extension)) {
        // Upload file to the server

    } else {
        // Handle error
        alert(`Please upload ${allowedExtensions.join(', ')} files`);
    }
});
        

Also Read: Check Internet Connection Offline/Online Using JavaScript in Browser

Conclusion

You have seen how to validate file types in 2 simple steps. Get the extension from the selected filename and check if it is allowed or not on your website.

In this way, users don't have to send the file to the server in order to know whether they are uploading a valid file or not. Everything will happen using JavaScript in the front end.

This technique is applicable to any type of file. It doesn't have to be the images. You can use it for any file extension validation in JavaScript before uploading to the server.

Related Posts