dpvp56187 2014-07-28 10:43
浏览 43
已采纳

如何在javascript中使用正则表达式验证文件扩展名

I have a text box with submit button.After clicking the submit button i want to check that filename is exist or not and also want to validate filename ( only .php extension is allowed) file extension.

<input type="text" name="textfield1" id="text1" />

<input type="button" value="submit" name="submit" id="submit" onclick="login()"; />

<input type="reset" value="clear" id="reset" name="reset" />
</form>
  • 写回答

2条回答 默认 最新

  • dongshangan2074 2014-07-28 10:56
    关注

    Looks like an X-Y problem here. Here's a couple of things you should consider:

    • Checking if a file exists (on the server, presumably) can't reliably be done client-side
    • Any client-side validation is insufficient to say the least. It's not reliable
    • Why regex? There are better tools for the job here. Better, as in: more reliable, easier, and probably faster, too
    • Checking the extension alone won't cut it. The rest of the filename might be invalid, too.

    Be that as it may, why not check the last four chars in the file name. Given that you only allow .php extensions, a simple:

    var inputVal = inputElem.value.trim();
    if (inputVal.substr(-4).toLowerCase() === '.php')
    

    should do just fine. You can do the same thing server-side, too:

    if (strtolower(trim(substr($_POST['inputName'], -4))) === '.php')
    

    Of course, you'll still have to check the value the user submitted for other prohibited/tricky chars like quotes, spaces, line-breaks, (back-)slashes, hashes and the like... All in all, I think you'd do well rethinking your approach. Perhaps tell us what it is you're actually trying to do, so we can recommend an alternative to your current solution.

    Once you've got that working, checking if a file actually exists can be easily done using the PHP function: file_exists. It returns true if the file exists, fals if not.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用