Home > Back-end >  Input file does not run function if empty
Input file does not run function if empty

Time:11-02

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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." );
    }
}
  • Related