Reputation: 1783
<input type="file" accept=".jpg">
This makes the file selection dialog default to only allowing JPG files, however there's also a dropdown menu for selecting All Files: All Files (*.*)
. How can I make it ONLY allow JPG files and not to have the option to select All Files in the dropdown?
Upvotes: 10
Views: 17868
Reputation: 942
Hi you can try this one
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
Or simply:
<input type="file" name="myImage" accept="image/*" />
<input type="file" accept=".png, .jpg, .jpeg" />
Upvotes: -3
Reputation: 200
Disabling the capability to select all files is already outside the scope of the browser, but there are still browsers who accept it such as Chrome 16 +, mSafari 6 +, mFirefox 9 +, mIE 10 +, mOpera 11 +
Try this one
<input type="file" accept="image/*">
//This will match all image files
Upvotes: 0
Reputation: 14541
You can't prevent the browser from offering the "All Files" options.
The accept attribute doesn't validate the types of the selected files; it simply provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.
Because of this, you should make sure that the accept attribute is backed up by appropriate server-side validation.
However you could attach an event listener to the file input, and if an invalid file is selected, you can reject it - with appropriate error message. This serves as an additional validation at the client side.
Note that this is not a substitute to the file validation at the server side.
You can see an example of such an event handler in snippet:
var fileInput = document.getElementById("fileinput");
var allowedExtension = ".jpg";
fileInput.addEventListener("change", function() {
// Check that the file extension is supported.
// If not, clear the input.
var hasInvalidFiles = false;
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
if (!file.name.endsWith(allowedExtension)) {
hasInvalidFiles = true;
}
}
if(hasInvalidFiles) {
fileInput.value = "";
alert("Unsupported file selected.");
}
});
<input type="file" accept=".jpg" id="fileinput">
Also, in case you want to allow all images, you can specify accept="image/*"
as the attribute. It will allow all image types, and in case of mobile devices allow the user to take pictures as well.
Upvotes: 17