如何从输入字段验证onchange文件名?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (89)

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-zA-Z0-9]\s\,\.\-\_

将表达式部分更改为:

[a-zA-Z0-9\s\,\.\-\_]
用户回答回答于

你的regexp需要字母或数字,需要“空格”、逗号、点

   /[a-zA-Z0-9\s\,\.\-\_]{5,50}\.(?:jpg|jpeg)$/i

扫码关注云+社区

领取腾讯云代金券