Validate file extension

4

I have a code that checks the size before sending the file, I would like to know how to check the file extension along, for example, I need these extensions .jpg, png, .gif, .pdf, .txt, .doc, .docx . Would I have to do in the same code? How would I do that?

Code

$j(function () {
  $j("#arquivo").change(function () {//ou Id do input 
    var fileInput = $j(this);
    var maxSize = $j(this).data('max-size');
    console.log(fileInput.get(0).files[0].size);

    //aqui a sua função normal
    if (fileInput.get(0).files.length) {
      var fileSize = fileInput.get(0).files[0].size; // in bytes
      if (fileSize > maxSize) {
        $j('#resultado').text('Arquivo excedeu o limite permitido, por favor escolha arquivos com no maximo 2GB*');
        $j('#validate').attr('disabled', 'disabled');
      } else {
        $j('#validate').removeAttr('disabled');
        $j('#resultado').hide();
      }
    }
  });
});
    
asked by anonymous 24.08.2017 / 22:51

3 answers

3

It is possible, because the value attribute of the input returns the file name:

$j(function () {
    $j("#arquivo").change(function () {//ou Id do input 
        var fileInput = $j(this);
        var maxSize = $j(this).data('max-size');
        var extPermitidas = ['jpg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx'];
        console.log(fileInput.get(0).files[0].size);

        //aqui a sua função normal
        if (fileInput.get(0).files.length) {
            var fileSize = fileInput.get(0).files[0].size; // in bytes
            if (fileSize > maxSize) {
                $j('#resultado').text('Arquivo excedeu o limite permitido, por favor escolha arquivos com no maximo 2GB*');
                $j('#validate').attr('disabled', 'disabled');
            } else if(typeof extPermitidas.find(function(ext){ return fileInput.val().split('.').pop() == ext; }) == 'undefined') {
                $j('#resultado').text('Extensão inválida');
                $j('#validate').attr('disabled', 'disabled');
            } else {
                $j('#validate').removeAttr('disabled');
                $j('#resultado').hide();
            }
        }
    });
});

Follow the example in action:

function verificaExtensao($input) {
  var extPermitidas = ['jpg', 'png', 'gif', 'pdf', 'txt', 'doc', 'docx'];
  var extArquivo = $input.value.split('.').pop();

  if(typeof extPermitidas.find(function(ext){ return extArquivo == ext; }) == 'undefined') {
    alert('Extensão "' + extArquivo + '" não permitida!');
  } else {
    alert('Ok!');
  }
}
<input type="file" onchange="verificaExtensao(this)">
    
24.08.2017 / 23:02
1

You can use a regex to validate if the file contains a certain extension.

Example

let validos = /(\.jpg|\.png|\.gif|\.pdf|\.txt|\.doc|\.docx)$/i;

$("#arquivo").change(function() {

  let fileInput = $(this);
  let nome = fileInput.get(0).files["0"].name;
  if (validos.test(nome)) {
    console.log("Válido")
  } else {
    console.log("Inválido")
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" id="arquivo">
    
24.08.2017 / 23:03
0
var extensao = $(this).val().split("\").pop().substring($(this).val().split("\").pop().lastIndexOf('.')+1, $(this).val().split("\").pop().length) || $(this).val().split("\").pop();

Use this code after the size check, or, together with it. Basically the code is taking the patch from the file that is in the input and extracting its extension, so you can do some conditionals and just accept the extensions you want.

Caution when using this type of validation with javascript, it can be easily fooled, so always use it in conjunction with a back-end check.

    
24.08.2017 / 23:02