1

I'm trying to validate file extensions in javascript. When I use just one argument in my if statement like this

     if(ext!='png' ){
                bodyAppend("err","Incorrect file type");
                bodyAppend("br","");
        }

the code works. But if I add an or statement like this

    if(ext!='png' || ext!='jpg'){
                bodyAppend("err","Incorrect file type");
                bodyAppend("br","");
        }

the code does not work and always returns true.

0

4 Answers 4

4

You need to use &&, not ||

The problem with the logic:

ext!='png' || ext!='jpg'

is that as soon as the extension is one of those options ("png" or "jpg"), it's NOT the other, so the opposite comparison will always be true. If it's "png", it's NOT "jpg". If it's "jpg", it's NOT "png".

I have this problem a lot with SQL queries. When you're writing out a condition with many comparisons, just try saying it out loud. If the extension is NOT "png" and the extension is NOT "jpg", then throw an error.

Sign up to request clarification or add additional context in comments.

Comments

2

@anpgall's answer is correct, but if you end up with a large number of extensions to check, this code might be easier to maintain.

// At the top of your function
var imageExts = ['png', 'jpg', 'gif'];

// later
// Perhaps setting ext to lower case.
if (imageExts.indexOf(ext)  === -1) {
  bodyAppend("err","Incorrect file type");
}

If you need to target older versions of IE, you can include this polyfill

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf

2 Comments

Very good point! That's usually the way I handle checking something against a long list of things - I was just trying to fix the immediate problem. And nice adding the IE fix :)
@ianpgall -- full ACK there. Actually answering the OPs question isn't a bad thing ;)
1

My guess is you need && (and), not || (or).

With &&, it is false only if the extension is not equal to both of them.

With ||, it is true if for instance ext === 'png' because the other condition will return true (and hence the entire condition be true) because it is !== to 'jpg'.

Comments

0

I would suggest this way of validating the file extension in JavaScript using jQuery:

HTML

<input id="file" type="file" class="findDocumentGeneral">

Javascript/Jquery

var extension = $('.findDocumentGeneral').val().split('.').pop().toLowerCase();
if (~$.inArray(extension, ['jpg', 'jpeg', 'gif', 'png', 'pdf', 'docx'])) {
    alert(extension); // to see if it works correctly
} else {
    alert("Incorrect file type.");
}

It's readable and works perfectly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.