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 files to upload. Client-side validation is more user-friendly than server-side. It will be a good idea to validate the 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.
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; 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]); } } }
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>
Here we have shown only the image file type validation, you can use this same script for other file types validation. You only need to specify the allowed file extensions on allowedExtensions
variable in JavaScript code. Apart from the file type validation, this script will help to display image preview without upload using JavaScript.
Do you want to get implementation help, or enhance the functionality of this script? Click here to Submit Service Request
Thanks a lot.
Thanks a lot for this tutorial.
thanks very much, its helpful
if this works, if the file name such as file.php.jpg ???
Yes, it will work.
Thanks for sharing this tutorial. it’s help me a lot.
thanks for working codes.
Thanks for the short and useful tutorial.