javascript jQuery Validate 图像扩展案例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22677241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Validate image extension case
提问by raygo
I am using jquery validate to validate image upload extension. Right now I have something like:
我正在使用 jquery 验证来验证图像上传扩展。现在我有类似的东西:
$("#photo").rules("add", {
accept: "jpg|jpeg|png|"
});
The problem is that this would only accept if the extension is lower case. I could do
问题是,这仅在扩展名是小写时才会接受。我可以做
$("#photo").rules("add", {
accept: "jpg|jpeg|png|JPG|JPEG|PNG"
});
But I would like this to work even if the extension is jPG or JPg. I tried this regex:
但即使扩展名是 jPG 或 JPg,我也希望它可以工作。我试过这个正则表达式:
accept: "/\.(jpe?g|gif|png)$/i"
Don't know if my regex is wrong or if the plugin just doesnt accept regex. Any idea? Thanks!
不知道我的正则表达式是错误的还是插件不接受正则表达式。任何的想法?谢谢!
回答by Sparky
accept
is only for mime types.
accept
仅适用于 mime 类型。
You need the extension
rule if you want to specify by file extension.
extension
如果要按文件扩展名指定,则需要该规则。
回答by SmilingSun
Perhaps you don't need bother jQuery to validate image extention.
也许您不需要麻烦 jQuery 来验证图像扩展。
If you don't care about case-sensitivity, you just need to use accept
attribute of <input>
to do it, just like this
如果你不关心大小写敏感,你只需要使用accept
属性<input>
来做到这一点,就像这样
<input type="file" name="pic" accept=".png, .jpg">
<input type="file" name="pic" accept=".png, .jpg">
but this solution has some compatibility limitation, see: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Browser_compatibility
但此解决方案有一些兼容性限制,请参阅:https: //developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Browser_compatibility