0

I'm trying to validate the file extension of a input type="file" field. But even if I upload a correct file it gives me error. I've read W3Schools and other sites and I can't see whats wrong with my code:

http://pastebin.com/GwE0aVaf - It's the IF-statement at the bottom of the first function.

Thanks in advance.

DoobyScooby
  • 367
  • 3
  • 6
  • 17

1 Answers1

2

The problem is that in the if statement it will always be true. You got:

if(fileName.lastIndexOf(".jpg") == -1 || fileName.lastIndexOf(".png") == -1)

And one of them will always be true wich causes the whole expressiont o be true. Probably you will want to use AND(&&) instead of OR(||).

if(fileName.lastIndexOf(".jpg") == -1 && fileName.lastIndexOf(".png") == -1)

The solves the imediate problem, but this type of check will always be faulty, since if the filename is some like "c:\sample.jpg.zip" it will be valid.

You should validate if the extension is in the end of the string with a endsWith() function or apropriate Regex.

See more at endsWith in JavaScript.

Community
  • 1
  • 1
svrx
  • 634
  • 4
  • 11