None of the existing answers seemed quite compact enough for the simplicity of the request. Checking if a given file input field has an extension from a set can be accomplished as follows:
function hasExtension(inputID, exts) {
var fileName = document.getElementById(inputID).value;
return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName);
}
So example usage might be (where upload
is the id
of a file input):
if (!hasExtension('upload', ['.jpg', '.gif', '.png'])) {
// ... block upload
}
Or as a jQuery plugin:
$.fn.hasExtension = function(exts) {
return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test($(this).val());
}
Example usage:
if (!$('#upload').hasExtension(['.jpg', '.png', '.gif'])) {
// ... block upload
}
The .replace(/\./g, '\\.')
is there to escape the dot for the regexp so that basic extensions can be passed in without the dots matching any character.
There's no error checking on these to keep them short, presumably if you use them you'll make sure the input exists first and the extensions array is valid!
jquery.ProgressBar.js
. It works, fine. ### So, can i validate with uploadify!!! – Gumboil