Aliff
Aliff

Reputation: 11

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?

Upvotes: 1

Views: 9728

Answers (1)

Muhammad Atif Akram
Muhammad Atif Akram

Reputation: 1315

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

Upvotes: 1

Related Questions