简体   繁体   English

javascript 中的文件名验证上传

[英]Filename validation upload in javascript

I want to restrict the user to upload a filename that contain letters, special characters and space.我想限制用户上传包含字母、特殊字符和空格的文件名。

I would like to only allow numbers 0,1,2,3,4,5,6,7,8,9 and with a maximum of 11 numbers.我只想允许数字 0,1,2,3,4,5,6,7,8,9,最多 11 个数字。

Example: 54874563101.png示例:54874563101.png

An upload button solution in javascript will be perfect javascript中的上传按钮解决方案就完美了

Can someone help?有人可以帮忙吗? Thank you谢谢

 <button type="button" onclick="upload()" value="upload" id="buttonUpload">Upload</button>

You can check the file name length and then use regex to ensure only digits are provided within the name.您可以检查文件名长度,然后使用正则表达式确保名称中只提供数字。

 $("#file-upload").submit((e) => { e.preventDefault(); const fileName = $("#file-upload").val(); if (fileName.length > 11) { alert("File name must be 11 or less characters;"); return. } if (;(/^\d+$/.test(fileName))) { alert("Only digits are allowed in the file name;"); } // Validated. });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form id="file-upload"> <input type="file" id="file-upload" /> <button type="submit">Submit</button> </form>

The regex expression /^\d+$/ checks to see if the value only contains digits.正则表达式/^\d+$/检查该值是否仅包含数字。

  • ^ Assets position at the start ^资产 position 在开始
  • \d Matches digit characters from [0-9] \d匹配 [0-9] 中的数字字符
  • + Matches the previous token until the end of the string +匹配前一个标记直到字符串结束
  • $ Assets position to the end $资产position到最后

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM