Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
Input file does not run function if empty

If I insert png it works, if I insert jpg it works, but if I leave the file empty it doesn't work, why? The file should be png or empty.

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0].type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || fileTypecheck.length == 0){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file"  onchange="loadFile(event)" accept="image/png">

<button onclick="myFunction()">Click me</button>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

When there is no file the index of files[0] does not excist. You can add a question mark (Optional_chaining) to files[0] so it does not break down when there are no files. Then you can change fileTypecheck.length== 0 to !fileTypecheck since it will be undefined when there is no file.

function myFunction() {
  var fileTypecheck = document.getElementById("file").files[0]?.type.replace(/(.*)\//g, '');
  
  if(fileTypecheck == "png" || !fileTypecheck){
  
      alert("File is png or 0");
  }else{
      alert("File is NOT png or 0");
  }
}
<input type="file" name="file" id="file" accept="image/png">

<button onclick="myFunction()">Click me</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

When an <input type="file"/> has no files selected its HTMLInputElement.files property is empty, so files[0] is undefined.

BTW, you should not rely on the browser to always accurately tell you of a file's type: browsers typically populate the File.type property from their host OS's file-extension-to-MIME-type registry which is not reliable and often outdated.

That said, change your code to this: note that I've added defensive programming steps to actually verify things instead of making assumptions:

function myFunction() {

    const inp = document.getElementById("file");
    if( !inp || inp.type !== 'file' ) throw new Error( "'file' input element not found." );
    
    if( inp.files.length !== 1 ) {
        alert( "Please select a single file first." );
        return;
    }

    const file = inp.files[0];
    if( file.type === 'image/png' ) {
        // OK
    
    }
    else {
        alert( "Please select a PNG file." );
    }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda