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

280
Views
React file validation

I have a question regarding my file validation on ReactJS.

I have else if statement in my code. When I try the code below and upload an image with jpg/png, it console.log("1st").

const fileChange = e => {
    const file = e.target.files[0];

    if(file === undefined) {
        console.log("undefined")
    
    } else if(file.type === "image/png" || file.type === "image/jpeg") {
        console.log("1st")
    
    } else {
        console.log("3rd")
    }
}

But when I tried the code below, it console.log("1st") instead of console.log("3rd").

const fileChange = e => {
    const file = e.target.files[0];

    if(file === undefined) {
        console.log("undefined")
    
       } else if(file.type !== "image/png" || file.type !== "image/jpeg") {
        console.log("1st")


    } else {
        console.log("3rd")
    }
}

Why does my first code worked and not the second one?

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

0

This answer is very simple explaining to your question

 const fileChange = e => {
    if(e.target.files.length < 1){
      return;
    }
    const file = e.target.files[0];
    switch(file.type){
      case 'image/png':
        //('image type is png');
        break;
      case 'image/jpg':
        //('image/jpg')
        break;
      case 'image/jpeg':
        //('image is jpeg')
        break;
      default:
        // image extension is not valid
    }
}

or if you only want to check for valid extension at one go then you can use the following snippet idea e.g

const isValidFileUploaded=(file)=>{
  const validExtensions = ['png','jpeg','jpg']
  const fileExtension = file.type.split('/')[1]
  return validExtensions.includes(fileExtension)
}

const fileChange = e => {
    if(e.target.files.length < 1){
      return;
    }
    const file = e.target.files[0];
    if(isValidFileUploaded(file)){
      //file is valid
    }else{
      //file is invalid
    }
}
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!