Last active
December 30, 2015 11:39
-
-
Save N-Porsh/7823876 to your computer and use it in GitHub Desktop.
JavaScript: File uploader validator
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
<script> | |
function unique(arr) { | |
var obj = {}; | |
for(var i=0; i<arr.length; i++) { | |
var str = arr[i]; | |
obj[str] = true; // запомнить строку в виде свойства объекта | |
} | |
return Object.keys(obj); // или собрать ключи перебором для IE<9 | |
} | |
$(function() { | |
var status = $('#status'); | |
//$('#myFile').bind('change', function() { | |
$("form").submit(function(file, ext) { | |
var maxFileSize = 3*1024*1024; | |
var fileUpl = $("#myFile").val(); | |
var files = $('#myFile').prop("files"); | |
var errors = []; | |
if(fileUpl != ''){ | |
//files will be a FileList object. | |
var names = $.map(files, function(val) { | |
return val.name.split('.').pop().toLowerCase(); // get ext of each file | |
}); | |
// check for valid file extension *********************** | |
$.each(names, function(i) { | |
if($.inArray(names[i], ['rar','zip','7z','pdf','xlsx','xls','docx','doc','txt']) == -1){ | |
errors.push("type"); | |
} | |
});// END check for valid file extension *********************** | |
// check size of each FILE ********************************** | |
//files will be a FileList object. | |
var nameSize = $.map(files, function(val) { | |
return val.size;// get size of each file | |
}); | |
// check each file in loop | |
$.each(nameSize, function() { | |
var num = (this/(1024*1024)); | |
if(this > maxFileSize){ | |
errors.push("size"); | |
} | |
}); // END. check size of each FILE ********************************** | |
// ************** check if any error exists and display error msg to user | |
var error_arr = []; | |
error_arr = unique(errors); // array of errors type | |
if(error_arr.length >0){ | |
if(error_arr.length >1 ) | |
status.text('File type and size are incorrect'); | |
else if(error_arr[0] == "type") | |
status.text('Only pdf, word, excel and archives are allowed').css("color","red"); | |
else if(error_arr[0] == "size") | |
status.text("One of the files is too large(file cannot be uploaded).Please read \"Upload notes\" ").css("color","red"); | |
return false; | |
}// ************** END of checking errors | |
} | |
});// end of submit form btn | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment