Validate file extension

Asked

Viewed 6,672 times

4

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

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();
      }
    }
  });
});

3 answers

5


It is possible, because the attribute value 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)">

  • I tried this, but it error to any extension. It displays the message even if the extension is png, jpg, etc..

  • @Gustavosouza Sorry Gustavo, there was a glitch in the if, test now please

  • It’s not working yet, if you want to take a test there to see

  • I set the name of its variable within the function and isolated the text, updated response ;)

  • I couldn’t do it by merging the 2 in 1 only, but I used your example separately and do what I need, it would be nice if the two of you worked together, but it’s functional, thank you.

  • There is another question, if I put a file and it is invalid, when I remove it and do not put another in place it continues with the visible error, would have to put if there is no file it "take out" the error?

  • at the event change, you can put an IF to check if the input field value is empty, if it is, you give an Hidden display or something like that in your msg

  • Thank you for the code, it worked perfectly. Thank you

Show 3 more comments

1

You can use a regex to validate whether 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>
<input type="file" id="arquivo">

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 size check, or in conjunction with it. Basically the code is taking the patch of the file that is in the input and, extracting its extension, with this, you can make some conditional and just accept the extensions you want.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.