AnApprentice
AnApprentice

Reputation: 110950

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

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

Upvotes: 16

Views: 62120

Answers (6)

Bablu Ahmed
Bablu Ahmed

Reputation: 5010

You can try like this

// Image upload validation
$(document).on('change', ':file',function () {
    const file = this.files[0];
    const fileType = file['type'];
    const validImageTypes = ['image/jpeg', 'image/png'];
    if (!validImageTypes.includes(fileType)) {
        alert('Only JPEG and PNG file types are allowed');
        this.value = '';
    }
});

Upvotes: 1

vp_arth
vp_arth

Reputation: 14982

How can we to check, that user selects image file?

  • By file extension validation
    It's work as expected, text file with .png extension pass here
  • input[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]);
    });
    

Upvotes: 1

Hardik Sondagar
Hardik Sondagar

Reputation: 4495

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/*'> 

Upvotes: 9

Jess Telford
Jess Telford

Reputation: 13200

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.

Upvotes: 30

Dr.Molle
Dr.Molle

Reputation: 117314

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.

Upvotes: 1

Alex
Alex

Reputation: 65934

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.

Upvotes: 7

Related Questions