Javascript在上传之前验证文件名 [英] Javascript validate filename before upload

查看:93
本文介绍了Javascript在上传之前验证文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想验证正在上传的图片的文件名,以确保它没有空格或不寻常的字符。

I simply want to validate the filename of the image being uploaded to ensure that it does not have spaces or unusual characters.

这是我最近的搜索尝试,还是没有运气。它可能与文件的路径有关吗?是考虑到这个还是只考虑文件名?

This is my latest attempt from searching around, still no luck. Could it be something to do with the path of the file? is it taking this or just the file name into account?

我有这个并且用php检查扩展工作服务器端,但我想提示一下用户在提交之前。

I have this and a check of the extention working server side with php, but I would like a prompt to the user before submitting.

此时即使我使用文件名,我也应该接受警报,或者它应该接受它。

At this point in time im getting the alert pop up even whether i use a file name it should accept or one that it should reject.

JavaScript

JavaScript

function validate(elem){
    var alphaExp = /^[a-zA-Z_-]+$/;
    if(elem.value.match(alphaExp)){
        return true;
    }else{
        alert("File name not suitable");
        elem.focus();
        return false;
    }
}

HTML

<label for="file">Filename:</label>
<input type="file" name="filename" id="filename" onchange="validate(this)" /> 
<p><input type="submit" name="submit" class="submit" value="Submit" />
</form>


推荐答案

您需要使用更复杂的正则表达式为此,因为您正在检查的 elem.value 将不会像 image123.jpg ,但更像是 C:\ fakepath\randomfolder \ some some folder\ image123.jpg

You will need to use a much more complex regular expression for this, because the elem.value you are checking won't be something like image123.jpg but more something like C:\fakepath\randomfolder\some other folder\image123.jpg

你可能想要请查看: http:// www .codeproject.com / Tips / 216238 / Regular-Expression-to-validate-file-path-and-exten

你会发现的例子这个页面主要用于文档,而不是图像,但你可以扭曲它以满足你的需求,如下所示:

The exemple you'll find on this page is mostly for documents, not images, but you can twist it a bit to fit your needs like this :

^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(png|gif|jpg|jpeg)$

这篇关于Javascript在上传之前验证文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆