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()
{
var extension= /* I know that the code to cut the extension off of the file
is working correctly so for now let's just go with it ok */
if(extension!="jpg" || "gif" || "bmp" || "png" || "whatever else")
alert("The file extension you have entered is not supported");
}
But this does not work. I have tracked it down to the if statement because if I select only 1 kind of file to check for, then it will work correctly. So my question to you is what the hell do I have to change to make this thing work correctly. I've been on this for about three hours now and it's driving me mad. Thanks for all of the help in advance.
You should be using
&&
instead of||
and you must prefix the!=
operator withextension
on each condition, not just the first one:As an alternative to the verbosity, use a regex:
You have to compare the variable
extension
for each tested extension. A compact way to do this would be:That's a syntax and a logic error. It should be:
Furthermore, you could handle it a little more succinctly with a regular expression:
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 ofextensions
is one of the supported values, you would change the logic from not equal/and to equal/or, like so:And again, it'd be more concise using a regular expression:
You need to include the parameters to compare in each clause.
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
&&
.The other answers have shown you how your javascript logic for multiple comparisons is wrong. But, a much better way to do this is to use a javascript map like this:
The is a easier to maintain by just adding/removing items to/from the
allowedExtensions
object.