[英]JavaScript: Validate form field (image extension)
I'm trying to validate the file extension of a input type="file" field. 我正在尝试验证input type =“file”字段的文件扩展名。 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:
我已经阅读了W3Schools和其他网站,我看不出我的代码有什么问题:
http://pastebin.com/GwE0aVaf - It's the IF-statement at the bottom of the first function. http://pastebin.com/GwE0aVaf - 这是第一个函数底部的IF语句。
Thanks in advance. 提前致谢。
The problem is that in the if statement it will always be true . 问题是在if语句中它始终是真的 。 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( || ).
可能你会想要使用AND( && )而不是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. 解决了中级问题,但这种类型的检查总是有问题,因为如果文件名是“c:\\ sample.jpg.zip” ,它将是有效的。
You should validate if the extension is in the end of the string with a endsWith() function or apropriate Regex. 您应该使用endsWith()函数或适当的Regex验证扩展名是否在字符串的末尾 。
See more at endsWith in JavaScript . 在JavaScript中查看更多内容 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.