Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

285
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda