Skip to content Skip to sidebar Skip to footer

Javascript If Statement Used To Check File Extensions Not Working

I have a form in which people can enter file paths. I want to make sure that the paths they are entering point to pictures so here is what I thought would work. function checkExt()

Solution 1:

That's a syntax and a logic error. It should be:

if (extension != "jpg" && 
    extension != "gif" && 
    extension != "bmp" && 
    extension != "png" && 
    extension != "whatever else") {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}

Furthermore, you could handle it a little more succinctly with a regular expression:

if (!/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is NOT one of the expected 
    // extensions.
}

Addendum:

The examples above execute the body of the if-statement when the value of extension is not one of the supported values. If you wanted to execute the body of the if-statement when the value of extensions is one of the supported values, you would change the logic from not equal/and to equal/or, like so:

if (extension == "jpg" || 
    extension == "gif" || 
    extension == "bmp" || 
    extension == "png" || 
    extension == "whatever else") {
    // This will execute when the extension is one of the expected extensions.
}

And again, it'd be more concise using a regular expression:

// I just removed the leading ! from the test case.
if (/jpg|gif|bmp|png|whatever/.test(extension)) {
    // This will execute when the extension is one of the expected extensions.
}

Solution 2:

As an alternative to the verbosity, use a regex:

if (extension.search(/jpg|gif|bmp|png/) === -1) {
    alert("The file extension you have entered is not supported.");
}

Solution 3:

You should be using && instead of || and you must prefix the != operator with extension on each condition, not just the first one:

if (extension != "jpg" &&
    extension != "gif" &&
    extension != "bmp" && 
    extension != "png" &&
    extension != "whatever else")

Solution 4:

You need to include the parameters to compare in each clause.

if( extension != "jpg" || 
    extension != "gif" || 
    extension != "bmp" || 
    extension != "png" || 
    extension != "whatever else"){
 //TODO: handle condition
}

As others have noted, this is a logical error in that if "jpg" is the extension the condition will still be hit because "jpg" != "gif". You might want to consider using &&.


Solution 5:

You have to compare the variable extension for each tested extension. A compact way to do this would be:

var extension = whatever;
var supportedExtensions = ["jpg","gif","bmp","png",... whatever else];
if (supportedExtensions.indexOf(extension) < 0) alert("Unsupported extension");

Post a Comment for "Javascript If Statement Used To Check File Extensions Not Working"