'How can I validate the file type selected from an input element of type file
I am trying to allow users to upload an image by using the html below
<input class="file-upload" id="imagepath" name="imagepath" type="file" accept="image/x-png,image/jpeg" />
Is there any way to show a validation message if a user selects a file that is not of the correct type using JS/JQuery?
I understand that the 'accept' attribute restricts what a user will see when they are viewing the file explorer however this can be changed using the drop down, to 'All files'.
Solution 1:[1]
You can fetch the extension of an uploaded file.
var files = event.target.files;
var filename = files[0].name;
var extension = files[0].type;
And apply the check and allow whichever file type you wanted to allow. Say for images stuff.
if(extension == "jpeg" || extension == "jpg") {
//do you code
} else {
//display an error
}
Solution 2:[2]
I think J D already gave you a solid answer on how to check the file type.
I looked around and found an example on MDN which I modified a bit. It exists of a list of accepted file types, like the one in your accept
attribute and a function which will check if the type of a file matches the ones in your accept
attribute.
The isValidFileType
accepts a File
and and array
as arguments which then will check if the File.type
is present in the types
array. If it is it will return true and not it will return false.
Same principles as J D described but with a functional programming approach.
// The input element.
const imagePath = document.getElementById('imagepath');
// List of accepted file types, gotten from your input's accept property.
const acceptedFileTypes = imagePath.accept.split(','); // ['image/jpeg', 'image/x-png']
// Check if file has the correct type.
const isValidFileType = (file, types) => types.some(type => type === file.type);
So on your form element you should attach a change event listener. And in that listener loop over all of the files and check if they have the correct extension.
imagePath.addEventListener('change', (event) => {
// Check if every file has the accepted extension.
const filesAccepted = event.target.files.every(file =>
isValidFileType(file, acceptedFiles)
);
if (filesAccepted) {
// Files are accepted
} else {
// Files are not accepted.
}
});
Although J D's example is a lot more compact and to the point, this example provides reusability and prevents you from writing the same code twice, or more. Also extending the list of accepted types is as easy as adding them to the accept
attribute of the HTML element.
Solution 3:[3]
Thanks For the help guys,
This is the solution I went with in the end and works perfectly
<!--HTML-->
<div id="fileErrorMessage" class="hide" >file type is not suuported</div>
<input class="some-class" id="imagepath" name="imagepath" type="file" accept="image/x-png,image/jpeg" />
/*css*/
#fileErrorMessage {
color: red;
font-weight: bold;
}
.hide {
display: none;
}
//JavaScript
$('#imagepath').on('change', function (event) {
var files = event.target.files;
Array.from(files).forEach(x => {
if (!x.type.includes("jpeg") && !x.type.includes("jpg") && !x.type.includes("png")) {
$("#fileErrorMessage").removeClass("hide");
$('#imagepath').val('');
}
else if (!$("#fileErrorMessage").hasClass("hide")) {
$("#fileErrorMessage").addClass("hide");
}
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jaydeep |
Solution 2 | |
Solution 3 |