Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

87
Views
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">

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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();
  
  //gettting 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">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!