在 Laravel 中仅验证字母数字字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38646494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validate only alphanumeric characters in Laravel
提问by Alexander Lomia
I have the following code in my Laravel 5 app:
我的 Laravel 5 应用程序中有以下代码:
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 underscoreswithin them. However, my regex is not working, it fails even on a single letter. What am I doing wrong?
我的意图是允许文件名中只包含字母数字字符、破折号和下划线。但是,我的正则表达式不起作用,即使在单个字母上也失败。我究竟做错了什么?
回答by Wiktor Stribi?ew
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.
您需要确保模式匹配整个输入字符串。此外,字母数字和下划线符号可以与 匹配\w,因此正则表达式本身可以大大缩短。
I suggest:
我建议:
'regex:/^[\w-]*$/'
Details:
详情:
^- start of string[\w-]*- zero or more word chars from the[a-zA-Z0-9_]range or-s$- end of string.
^- 字符串的开始[\w-]*-[a-zA-Z0-9_]范围或-s 中的零个或多个字字符$- 字符串的结尾。
Why is it better than 'alpha_dash': you can further customize this pattern.
为什么比'alpha_dash':您可以进一步自定义此模式。
回答by Akram Wahid
use laravel rule,
使用 Laravel 规则,
public function store(Request $request){
$this->validate($request, ['filename' => 'alpha_dash']);
}
Laravel validation rule for alpha numeric,dashes and undescore
回答by djt
Might be easiest to use the built in alpha-numeric validation:
可能最容易使用内置的字母数字验证:
https://laravel.com/docs/5.2/validation#rule-alpha-num
$validator = Validator::make($request->all(), [
'filename' => 'alpha_num',
]);
回答by Daniel Waghorn
You forgot to quantify the regex, it also wasn't quite properly formed.
您忘记量化正则表达式,它的格式也不太正确。
public function store(Request $request){
$this->validate($request, ['filename' => 'regex:/^[a-zA-Z0-9_\-]*$/']);
}
This will accept empty filenames; if you want to accept non-empty only change the *to +.
这将接受空文件名;如果你想接受非空只更改*为+.

