HTML
<form>
<input type="file" onchange="return validateSize()" id="uploadFile" accept="image/*">
<button type="submit">Send</button>
</form>
JavaScript
function validateSize() {
const file = document.querySelector('#uploadFile');
const file_name = file.value;
const extension = file_name.split('.').pop().toLowerCase();
const size = file.files[0].size;
const allowedFormats = ["jpg", "jpeg"];
if (((size/1024)/1024) > 4) {
// works perfect
alert("Please optimize your image to maximum 4MB!");
file.value = "";
return false;
}
else if (!(allowedFormats.indexOf(extension) > -1)) {
// works perfect
alert("Please save your image in JPG format!");
file.value = "";
return false;
}
else if ((/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i.test(file_name)) == false) {
// this IS NOT working
alert("Filename can have only letters (a-z), numbers, spaces, dots, '-' and '_'!");
file.value = "";
return false;
}
}
大小验证起作用。
扩展验证起作用。
文件名验证不起作用。
我希望有这个正则表达式条件:
/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i
如果文件名具有正则表达式中未包含的其他字符,则返回警报。
谢谢!
PS:你可以在https://jsfiddle.net/jacob19/a3fLog6r/5/测试代码,看看你是否能找到解决方案。
发布于 2018-08-19 13:44:37
您不是针对文件名进行检查,而是针对一个假路径进行检查,通常类似于"C:\fakepath\file_name.ext"
。
文件的名称可以作为您获得的文件对象的.name
属性进行访问:
var input = document.querySelector('input');
input.onchange = function(e) {
// grab the File object that has been selected by the user
var file_object = input.files[0];
// here you have the file's name
var file_name = file_object.name;
// now you can do your check
if ((/^[a-z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i.test(file_name)) == false) {
alert("Filename can have only letters (a-z), numbers, spaces, dots, '-' and '_'!");
input.value = "";
}
console.log("for info, the input's value was ", input.value);
console.log("while the file's name was ", file_name);
};
<input type="file">
发布于 2018-08-19 03:12:33
您的正则表达式需要字母或数字,还必须有‘空格’、逗号、点、-,_我想您是这个意思
/[a-zA-Z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i
发布于 2018-08-19 03:23:15
您在正则表达式中犯了一个小错误。这一位:
[a-zA-Z0-9]\s\,\.\-\_
表示:任何小写字母、任何大写字母或后跟空格字符、逗号、句点、破折号和下划线的任何数字。
[]
运算符表示选择。你应该移动里面的所有东西。
A-Z
语法只是ABCD...WXYZ
的简写。
将表达式部分更改为:
[a-zA-Z0-9\s\,\.\-\_]
https://stackoverflow.com/questions/51911636
复制相似问题