仅验证Laravel中的字母数字字符 [英] Validate only alphanumeric characters in Laravel
问题描述
我的Laravel 5应用程序中包含以下代码:
I have the following code in my Laravel 5 app:
public function store(Request $request){
$this->validate($request, ['filename' => 'regex:[a-zA-Z0-9_\-]']);
}
我的意图是允许文件名中仅包含字母数字字符,破折号和下划线.但是,我的正则表达式无法正常工作,即使是一个字母也无法正常工作.我在做什么错了?
My intentions are to permit filenames with only alphanumeric characters, dashes and underscores within them. However, my regex is not working, it fails even on a single letter. What am I doing wrong?
推荐答案
您需要确保模式与整个输入字符串匹配.另外,字母数字和下划线符号可以与\w
匹配,因此正则表达式本身可以大大缩短.
You need to make sure the pattern matches the whole input string. Also, the alphanumeric and an underscore symbols can be matched with \w
, so the regex itself can be considerably shortened.
我建议:
'regex:/^[\w-]*$/'
详细信息:
-
^
-字符串开头 -
[\w-]*
-零个或多个来自[a-zA-Z0-9_]
范围或-
s 的单词字符
-
$
-字符串结尾.
^
- start of string[\w-]*
- zero or more word chars from the[a-zA-Z0-9_]
range or-
s$
- end of string.
为什么比'alpha_dash'
好:您可以进一步自定义此模式.
Why is it better than 'alpha_dash'
: you can further customize this pattern.
这篇关于仅验证Laravel中的字母数字字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!