用于验证文件名的Javascript正则表达式 [英] Javascript regex for validating filenames

查看:135
本文介绍了用于验证文件名的Javascript正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个regexp来验证文件名。这是它:

I have a regexp to validate file names. Here is it:

/[0-9a-zA-Z\^\&\'\@\{\}\[\]\,\$\=\!\-\#\(\)\.\%\+\~\_ ]+$/

它应该允许这样的文件名:

It should allow file names like this:

aaa
aaa.ext
a#
A9#.ext

不允许使用以下字符 \ /:*? \<> |

问题是文件名如 * .txt / \\\kk 通过验证。我正在使用keyup事件进行验证。所以当我在不允许的情况下添加一个额外的字符后,它会显示一切正确。

The problem is that file names like *.txt or /\kk passes the validation. I am doing validation with keyup event. So when I put one extra character after not allowed one it shows that everything is correct.

推荐答案

你需要添加一个起始锚:

You need to add a starting anchor:

/^[0-9a-zA-Z ... ]+$/

这告诉引擎从输入的开始一直到输入的结尾匹配,而对于原始表达式,它只需要在输入的末尾匹配。

This tells the engine to match from the start of the input all the way to the end of the input, whereas for your original expression it only needs to match at the end of the input.

这篇关于用于验证文件名的Javascript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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