php Laravel 5.4 - 使用正则表达式验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42577045/
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
Laravel 5.4 - Validation with Regex
提问by Black
Below is my rule for project name:
以下是我对项目名称的规则:
$this->validate(request(), [
'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];
I am trying to add the rule such that it must start with a letter from a-z
or A-z
and can end with numbers but most not.
我正在尝试添加规则,使其必须以来自or的字母开头,并且可以以数字结尾,但大多数不是。a-z
A-z
Valid values for project name:
项目名称的有效值:
myproject123
myproject
MyProject
Invalid values for project name:
项目名称的无效值:
123myproject
!myproject
myproject 123
my project
my project123
I tried my regex online:
我在网上尝试了我的正则表达式:
https://regex101.com/r/FylFY1/2
https://regex101.com/r/FylFY1/2
It should work, but I can pass the validation even with project 123
.
它应该可以工作,但即使使用project 123
.
UPDATE: It actually works, I just tested it in the wrong controller, im sorry... but maybe it will help others nevertheless
更新:它确实有效,我只是在错误的控制器中测试了它,对不起......但也许它会帮助其他人
回答by Troyer
Your rule is well done BUTyou need to know, specify validation rules with regex separated by pipeline can leadto undesired behavior.
您的规则做得很好,但您需要知道,使用由管道分隔的正则表达式指定验证规则可能会导致不良行为。
The proper way to define a validation rule should be:
定义验证规则的正确方法应该是:
$this->validate(request(), [
'projectName' =>
array(
'required',
'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
)
];
You can read on the official docs:
您可以阅读官方文档:
regex:pattern
The field under validation must match the given regular expression.
Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
正则表达式:模式
验证字段必须与给定的正则表达式匹配。
注意:当使用 regex / not_regex 模式时,可能需要在数组中指定规则而不是使用管道分隔符,尤其是当正则表达式包含管道字符时。