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 Answers3

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.

Daniel Li
  • 14,976
  • 6
  • 43
  • 60
  • The variable extension won't contains the file extension if filename contains dots. – Édouard Lopez Jan 31 '13 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 Jan 31 '13 at 17:57
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?

Community
  • 1
  • 1
gustavodidomenico
  • 4,640
  • 1
  • 34
  • 50
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.

Joey
  • 1,651
  • 15
  • 30