File Type (extension) Validation with JavaScript

File type validation

File type validation before uploading to the server is obligatory for every file upload in the web application. Therefore, it helps to ensure that the user has selected the correct types of files to upload. Client-side validation is more user-friendly than the server-side. It would be a good idea to validate the file type before uploading. With the help of JavaScript, you can check the selected file extension with easily allowed file extensions. In this tutorial, we will explain to you how to implement file extension validation in JavaScript. Using our file type validation script, you can set a limit for the user to upload only the allowed file types.

In our sample script, we have validated image files using JavaScript and permits the user to select only .jpeg, .jpg, .gif, and .png type file. If the selected file extension is not matched with the specified types, then it will show the alert message to the user. Else, it will display the chosen image preview under the file input field.

JavaScript Code

The fileValidation() function have the complete file type validation code. This JavaScript feature 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;
    if(!allowedExtensions.exec(filePath)){
        alert('Please upload file having extensions .jpeg/.jpg/.png/.gif only.');
        fileInput.value = '';
        return false;
    }else{
        //Image preview
        if (fileInput.files && fileInput.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('imagePreview').innerHTML = '<img src="'+e.target.result+'"/>';
            };
            reader.readAsDataURL(fileInput.files[0]);
        }
    }
}

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

HTML Code

On file select, execute the  fileValidation() function. If the allowed file types are selected, then it will show image preview in  imagePreview  div.

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

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

SEE ALSO: How to Backup MySQL Database using PHP

Conclusion

Firstly, in our sample script, we have explained to you only the image file type validation. Therefore, you can use this same script for other file types validation. Secondly, you only have to specify the allowed file extensions on allowedExtensions variable in JavaScript code. At last, this script will help to display image preview without upload using JavaScript.

Also, read our previous blog- Send Email via SMTP Server in PHP using PHPMailer

Exit mobile version