None of the existing answers seemed compact enough for ease of request. Checking whether a given file input field can have an extension from a set can be performed as follows:
function hasExtension(inputID, exts) { var fileName = document.getElementById(inputID).value; return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test(fileName); }
So an example could be (where upload is the id to enter the file):
if (!hasExtension('upload', ['.jpg', '.gif', '.png']) {
Or as a jQuery plugin:
$.fn.hasExtension = function(exts) { return (new RegExp('(' + exts.join('|').replace(/\./g, '\\.') + ')$')).test($(this).val()); }
Usage example:
if (!$('#upload').hasExtension(['.jpg', '.png', '.gif'])) {
.replace(/\./g, '\\.') , regex dots should be avoided so that base extensions can be passed without dots matching any character.
There is no error checking them to be short, presumably if you use them, you will make sure that the input exists first, and the array of extensions is valid!
Orbling Jun 28 '13 at 1:38 2013-06-28 01:38
source share