AnA*_*ice 16 jquery jquery-plugins
我有以下内容:
<input id="user_profile_pic" name="user[profile_pic]" type="file">
Run Code Online (Sandbox Code Playgroud)
在服务器上,我检查以确保它是一个图像,但我想首先检查客户端.
如果选择的文件输入文件不是gif,jpg,png或bmp,我如何使用jQuery提醒用户?
谢谢
Jes*_*ord 28
您想要检查元素的值是什么,类似于:
$("#user_profile_pic").change(function() {
var val = $(this).val();
switch(val.substring(val.lastIndexOf('.') + 1).toLowerCase()){
case 'gif': case 'jpg': case 'png':
alert("an image");
break;
default:
$(this).val('');
// error message here
alert("not an image");
break;
}
});
Run Code Online (Sandbox Code Playgroud)
编辑
代码根据注释更改 - 现在删除所选文件的值(如果不是图像).
这很简单,不需要任何JavaScript验证.只需写这个,它只接受图像文件.
<input type="file" multiple accept='image/*'>
Run Code Online (Sandbox Code Playgroud)
您可以使用正则表达式:
var val = $("#user_profile_pic").val();
if (!val.match(/(?:gif|jpg|png|bmp)$/)) {
// inputted file path is not an image of one of the above types
alert("inputted file path is not an image!");
}
Run Code Online (Sandbox Code Playgroud)
当然,您可以为正则表达式添加更多格式.有更复杂和全面的方法来实现这一点,但只要输入的图像文件路径以标准图像文件扩展名结束,此方法就可以完成任务.
| 归档时间: |
|
| 查看次数: |
57656 次 |
| 最近记录: |