Check file type when form submit?
Instead of using onsubmit
, use jQuery's submit handler, and validate using some javascript like the following:
function getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isImage(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'gif':
case 'bmp':
case 'png':
//etc
return true;
}
return false;
}
function isVideo(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'm4v':
case 'avi':
case 'mpg':
case 'mp4':
// etc
return true;
}
return false;
}
$(function() {
$('form').submit(function() {
function failValidation(msg) {
alert(msg); // just an alert for now but you can spice this up later
return false;
}
var file = $('#file');
var imageChosen = $('#type-1').is(':checked');
if (imageChosen && !isImage(file.val())) {
return failValidation('Please select a valid image');
} else if (!imageChosen && !isVideo(file.val())) {
return failValidation('Please select a valid video file.');
}
// success at this point
// indicate success with alert for now
alert('Valid file! Here is where you would return true to allow the form to submit normally.');
return false; // prevent form submitting anyway - remove this in your environment
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="/gallery/create" method="post" enctype="multipart/form-data">
<label>Type:*</label>
<label for="type-1">
<input type="radio" checked="checked" value="1" id="type-1" name="type">Image
</label>
<label for="type-2">
<input type="radio" value="2" id="type-2" name="type">Video
</label> <br />
<label class="itemdetailfloatL required" for="file">File:*</label>
<input type="hidden" id="MAX_FILE_SIZE" value="8388608" name="MAX_FILE_SIZE">
<input type="file" tabindex="5" class="text-size text" id="file" name="file">
<br/>
<input type="submit" value="Create" id="submit" name="submit">
</form>
tested in IE8, RockMelt (based on Chrome) and Firefox 7: http://jsfiddle.net/Ngrbj/4/
Every File type has a 'type' property, for example: 'image/jpeg', 'audio/mp3' and so on...
This is an example for one way to check the type of the file by using the 'match' method (of strings):
function getFileType(file) {
if(file.type.match('image.*'))
return 'image';
if(file.type.match('video.*'))
return 'video';
if(file.type.match('audio.*'))
return 'audio';
// etc...
return 'other';
}
You can also write it the boolean way:
function isImage(
return !!file.type.match('image.*');
}