Ponraj Ponraj - 1 month ago 11
Javascript Question

Validate on select while choosing files for upload

I am trying to validate file types as soon as the files are choosen for upload

Below is my html code

<label> <input type="file" id="image" name="upload[]" multiple="multiple" onclick="validateFileExtension()" />


Validation code

function validateFileExtension() {
var ext = $('#my-file-selector').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg', 'pdf']) == -1) {
alert('invalid extension!');
}
}


But it is not validation as soon as the files are selected. Only upon submit the form, the validation happens. i have other a jquery for validation on submit. I need to validate on select. Please help out

Answer

onclick is not firing after you select a file. using onchange instead works.

function validateFileExtension(element) {
  var files = $(element)[0].files;
  for(var i = 0; i < files.length; i++) {
    var ext = files[i].name.split('.').pop().toLowerCase();
    if ($.inArray(ext, ['gif', 'png', 'jpg', 'jpeg', 'pdf']) == -1) {
      console.log('invalid extension!', ext);
    } else {
      console.log('valid extension :)', ext);
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="image" name="upload[]" multiple="multiple" onchange="validateFileExtension(this)" />

Comments