views:

5223

answers:

2

I would like to have jQuery limit a file upload feild to only jpg/jpeg, png, and gif. I am doing backend checking with php already. I am running my submit button through a javascript function already so I really just need to know how to check for the filetypes before submit or alert.

Thanks!

+11  A: 

You can get the value of a file field just the same as any other field. You can't alter it, however.

So to superficially check if a file has the right extension, you could do something like this:

var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
var allow = new Array('gif','png','jpg','jpeg');
if(jQuery.inArray(ext, allow) == -1) {
    alert('invalid extension!');
}
Paolo Bergantino
+5  A: 

You could use the validation plugin for jQuery: http://docs.jquery.com/Plugins/Validation

It happens to have an accept() rule that does exactly what you need: http://docs.jquery.com/Plugins/Validation/Methods/accept#extension

Note that controlling file extension is not bullet proof since it is in no way related to the mimetype of the file. So you could have a .png that's a word document and a .doc that's a perfectly valid png image. So don't forget to make more controls client-side ;)

Julian Aubourg