File Type (extension) Validation with JavaScript


File type validation before uploading to the server is mandatory for every file upload in the web application. It helps to ensure that the user has selected the correct types of file to upload. Client side validation is more user-friendly than server side. It will be a good idea to validate file type before submitting to upload. Using JavaScript, you can easily check the selected file extension with allowed file extensions.

In this tutorial, we will show how you can implement file extension validation in JavaScript. Using our file type validation script, you can restrict the user to upload only the allowed file types.

In our example script, we will validate image file using JavaScript and allow user to select only .jpg, .jpeg, .png, and .gif type file. If the selected file extension is not matched with the specified types, the alert message will be shown to the user. Otherwise, the chosen image preview will be displayed under the file input field.

JavaScript Code

The fileValidation() function contains the complete file type validation code. This JavaScript function needs to call for file extension validation.

function fileValidation(){
    var fileInput = document.getElementById('file');
    var filePath = fileInput.value;
    var allowedExtensions = /(\.jpg|\.jpeg|\.png|\.gif)$/i;
        alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
        fileInput.value = '';
        return false;
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="''"/>';

Image file extensions regex is defined in allowedExtensions variable. If you want to validate other file types, change the regex with allowed extensions.


On file select, the fileValidation() function will be executed. If the allowed file types are selected, image preview will be shown in imagePreview div.

<!-- File input field -->
<input type="file" id="file" onchange="return fileValidation()"/>

<!-- Image preview -->
<div id="imagePreview"></div>

Related Articles

Comments 0