用于验证文件名的Javascript正则表达式 [英] Javascript regex for validating filenames
问题描述
我有一个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屋!