I have the following:
<input id="user_profile_pic" name="user[profile_pic]" type="file">
On the server I check to make sure it's an image, but I want to check on the clientside first.
How with jQuery can I alert the user if the file input file selected isn't a gif,jpg,png, or bmp?
Thanks
You want to check what the value of the element is, something along the lines of:
$("#user_profile_pic").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'gif': case 'jpg': case 'png':
alert("an image");
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
});
Edit
Code changed based on comment - now removes the value of the selected file if not an image.
It's pretty simple not needed any JavaScript validations . Just write this and it'll accept only image files.
<input type="file" multiple accept='image/*'>
You could use a regular expression:
var val = $("#user_profile_pic").val();
if (!val.match(/(?:gif|jpg|png|bmp)$/)) {
// inputted file path is not an image of one of the above types
alert("inputted file path is not an image!");
}
Of course you could add more formats to the regular expression. There are more complex and comprehensive ways to accomplish this, but this method will accomplish the task as long as the image file path inputted ends in a standard image file extension.
There may be browsers that allow you to create a <img/>
of the given path, by that you could check if it's a real image or not(if not the onerror-event should fire on the image and it will have a width/height of 0).
But as this only works in some browsers and is an security-risk(in my mind) I would'nt suggest to do this, so my answer is: you can't validate there anything.
Checking the file-extensions like suggested by Alex may be an option, but the file-extension does not guarantee if it's a image. However, as a simple pre-check(not validation) it could be useful.
How can we to check, that user selects image file?
.png
extension pass hereinput[type=file][accept=image/*]
It initially hides non-image
files from user. But this filter works by extensions too. And user still can manually enter any existing file name.We can check mime type of result dataUrl
, it starts with data:mimetype;base64,...
. So, we need image/*
mimetype.
var file = $('#uploadfile');
file.on('change', function (e) {
var reader = new FileReader();
reader.onload = function() {
var data = reader.result;
if (data.match(/^data:image\//)) {
$('#thumbnail').attr('src', data);
} else {
console.error('Not an image');
}
};
reader.readAsDataURL(file.prop('files')[0]);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With