Skip to content

Instantly share code, notes, and snippets.

@absent1706
Created August 16, 2016 10:22
Show Gist options
  • Save absent1706/4051d7114b39af188189202ca81a1278 to your computer and use it in GitHub Desktop.
Save absent1706/4051d7114b39af188189202ca81a1278 to your computer and use it in GitHub Desktop.
// checks that all files in <input type="file"> have valid mime type (according to 'accept' attribute)
$.fn.filesHaveValidType = function() {
// this validation works for:
// 1. simple 'accept' values like 'image/*'
// 2. combined 'accept' values like accept="image/png, audio/mp3"
var elem = this[0];
var accept = this.attr('accept');
if (accept) {
var acceptTypes = accept.split(',').map(function(s) { return s.trim() });
// iterate over all files and return false if some file is of invalid type
for (var i = 0; i < elem.files.length; i++) {
var correctFileType = acceptTypes.some(function(acceptType) {
// .match() is used to compare, say, 'image/*' and 'image/png'
return elem.files[i].type.match(acceptType);
});
if (!correctFileType) {
return false;
}
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment