1

I am currently trying ot find a way to use jquery to validate if a a file is in picture format (jpeg,jpg,bmp,gif,etc). I have been able to figure out if the input is empty or not with simple .length comparison. How would I be able to check the file type and only accept valid picture formats.

Emtpy or not input:

if ($.trim($('#textInput').val()).length == 0) {
    alert("Should Not Be Empty!");
}

3 Answers 3

2

Given a file input:

var extension = $('#file_input').val().split('.').pop();
if (['bmp', 'gif', 'png', 'jpg', 'jpeg'].indexOf(extension) > -1) {
    console.log('validated');
} else {
    console.log('invalid extension');
}

For more extensive file-type filtering, you should ideally use server-side validation.

2
  • The variable extension won't contains the file extension if filename contains dots. Commented Jan 31, 2013 at 17:51
  • I was using split('.')[1] instead of split('.').pop(). Basically, if you had a filename like my.example.jpg, extension would've been example. This has since been fixed.
    – Daniel Li
    Commented Jan 31, 2013 at 17:57
2

For security reasons, you should not test for valid file types using javascript. Javascript is client-side only, therefore your script could easily be evaded or the user could simply rename their file with a separate extension and your checkpoint would fail.

Look into MIME types and server-side validation of user-upload files. It's a complicated subject and it's up to you to decide how much time you want to spend on it. Security increases with more thorough checks.

The checks I use are file size, MIME type, and upload location (to make sure no one is trying to upload a script from a remote site). These functions in PHP are filesize, fileinfo, mime_content_type, and is_uploaded_file. Similar functions exist in other languages.

You could go even further and test the bits of the file to ensure it is not malicious code or a file pretending to be a JPEG by tricking the MIME headers, for example.

2
  • 1
    + 1, I agree with you, but a client-side verification can also be done, mainly to avoid unnecessary server calls. Commented Jan 31, 2013 at 18:03
  • JavaScript can be server side with Node.js Commented May 2, 2014 at 1:41
2

You can make a simple function to extract the extension of the file:

function getExtension(file) {
    return file.split('.').pop();
}

And then you can check the input value:

var file = $.trim($('#textInput').val());
if (['gif','png', ...].indexOf(getExtension(file)) > - 1) {
     ...
}

And also check this post, maybe useful:

How to validade in HTML5 to only allow in 'input type="file"' JPG, GIF or PNG?