Alessandro Alessandro - 3 months ago 9
jQuery Question

Validating file extension on upload with Javascript

I want to validate file extension during upload, so I tried this:

HTML

<form name="userForm" ng-submit="submitForm()" novalidate>
<input class="upload-file" data-max-size="7048" data-min-size="2048" type="file" name="filename" ng-model="userForm.file" validfile>
</form>


focusing only on file extension validation I tried this:

JS

var extn = filename.split(".").pop();
var validFormats = ['mp3', 'wav'];
if validFormats.indexOf(extn) {
...
}


What is wrong with the syntax
if validFormats.indexOf(extn)
?

Answer

Just get the value and compare the last chars with the array values. indexOf will return the index if found in the array, or -1 if not. So you have to compare to it to -1. When found on the first entry in an array, the index is 0, what would be false otherwise.

$(function() {
    var validFormats = ['mp3', 'wav'];
  
    $('.upload-file').change(function(e) {
        var extn = $(this).val().split(".").pop();

        if( validFormats.indexOf(extn) == -1 ) {
            $(this).val('');
            alert('please only use one of the following filetypes: ' + validFormats.join(', '));
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="userForm" ng-submit="submitForm()" novalidate>
  <input class="upload-file" data-max-size="7048" data-min-size="2048" type="file" name="filename" ng-model="userForm.file" validfile>
</form>