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 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑