Skip to content
Advertisement

Js or jquery file.type.match for jpg and png only

How can I limit the mimetype for only png and jpg using file.type.match

below is my code

var fileInput = document.getElementById("myfileinput").files[0];

if (fileInput.type.match('image/jpeg'))  
      //I not thinking to use if(xx || xx)
      //prefer using var mimeType = jpg,png  many tries but not work
{
alert("Right");
}else{
alert("wrong");
}

Advertisement

Answer

from your question it sounds like you don’t want to do something like:

if (fileInput.type.match('image/jpeg') || fileInput.type.match('image/png'))  
  //I not thinking to use if(xx || xx)
  //prefer using var mimeType = jpg,png  many tries but not work
{
  alert("Right");
}else{
  alert("wrong");
}

You can make an array of acceptable extensions and loop through them like:

var fileInput = document.getElementById("myfileinput").files[0];
var allowed = ["jpeg", "png"];
var found = false;

allowed.forEach(function(extension) {
  if (fileInput.type.match('image/'+extension)) {
    found = true;
  }
})

if(found) {
  alert("Right");
}
else{
  alert("wrong");
}

See this fiddle for a test.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement