How can I limit the mimetype for only png and jpg using file.type.match
below is my code
JavaScript
x
11
11
1
var fileInput = document.getElementById("myfileinput").files[0];
2
3
if (fileInput.type.match('image/jpeg'))
4
//I not thinking to use if(xx || xx)
5
//prefer using var mimeType = jpg,png many tries but not work
6
{
7
alert("Right");
8
}else{
9
alert("wrong");
10
}
11
Advertisement
Answer
from your question it sounds like you don’t want to do something like:
JavaScript
1
9
1
if (fileInput.type.match('image/jpeg') || fileInput.type.match('image/png'))
2
//I not thinking to use if(xx || xx)
3
//prefer using var mimeType = jpg,png many tries but not work
4
{
5
alert("Right");
6
}else{
7
alert("wrong");
8
}
9
You can make an array of acceptable extensions and loop through them like:
JavaScript
1
17
17
1
var fileInput = document.getElementById("myfileinput").files[0];
2
var allowed = ["jpeg", "png"];
3
var found = false;
4
5
allowed.forEach(function(extension) {
6
if (fileInput.type.match('image/'+extension)) {
7
found = true;
8
}
9
})
10
11
if(found) {
12
alert("Right");
13
}
14
else{
15
alert("wrong");
16
}
17
See this fiddle for a test.