Search code examples
javascriptimagevalidationupload

Validate uploaded files by width and height in JavaScript


This code is working well. It restricts the type and size of the image before upload but in addition, I would like to restrict the maximum dimension width and height of the image before upload. I would like to restrict the upload if the width and height are not correct like the script below did for extension and size. Thank you!

document.getElementById("files").addEventListener("change", validateFile)

function validateFile(){
  const allowedExtensions =  ['jpg'],
        sizeLimit = 150000; 
        

  const { name:fileName, size:fileSize } = this.files[0];

  const fileExtension = fileName.split(".").pop();
  

  if(!allowedExtensions.includes(fileExtension)){
    alert("This is not a valid image");
    this.value = null;
  }else if(fileSize > sizeLimit){
    alert("This is not a valid image")
    this.value = null;
  }
}
    <input onchange="validateFile()" type="file" id="files" class="box_file">


Solution

  • Use clientWidth & clientHeight property for width and height and then apply your desired condition.

    var img = document.getElementById('files');
    img.addEventListener('change', function() {
        const allowedExtensions =  ['jpg'],
            sizeLimit = 150000;     
    
      const { name:fileName, size:fileSize } = this.files[0];
    
      const fileExtension = fileName.split(".").pop();
      
      // getting height & width
      var width = img.clientWidth;
      var height = img.clientHeight;
      
      let alrt = "";
    
      if(!allowedExtensions.includes(fileExtension)){
        alrt += "This is not a valid image! \n";
      }
      debugger;
      if(fileSize > sizeLimit){
        alrt += "This is not a valid image! \n";
      }
      
      if(width != 200 && height != 20 ){ //checking height & width
            alrt += "not a valid dimention! \n";
        }
        
        if(alrt){
         alert(alrt);
         img.value = null;
         return false;
        }
        else{
            alert("upload successful!");
            return true;
        }
    
    });
    <input type="file" id="files" class="box_file">