Created
August 16, 2016 10:22
-
-
Save absent1706/4051d7114b39af188189202ca81a1278 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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