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

286
Visualizações
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 Respostas
Responde à pergunta

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 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