How to have jQuery restrict file types on upload?
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();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
No plugin necessary for just this task. Cobbled this together from a couple other scripts:
$('INPUT[type="file"]').change(function () {
var ext = this.value.match(/\.(.+)$/)[1];
switch (ext) {
case 'jpg':
case 'jpeg':
case 'png':
case 'gif':
$('#uploadButton').attr('disabled', false);
break;
default:
alert('This is not an allowed file type.');
this.value = '';
}
});
The trick here is to set the upload button to disabled unless and until a valid file type is selected.