jQuery - INPUT type=File , Image FileType Validation options?

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.


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.