Laravel 5.4-使用正则表达式进行验证 [英] Laravel 5.4 - Validation with Regex
问题描述
以下是我的项目名称规则:
$this->validate(request(), [
'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];
我正在尝试添加规则,使其必须以a-z
或A-z
中的字母开头,并且可以以数字结尾,但大多数不能以数字结尾.
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.
项目名称的有效值:
myproject123
myproject
MyProject
项目名称的无效值:
123myproject
!myproject
myproject 123
my project
my project123
我在线尝试了正则表达式:
I tried my regex online:
https://regex101.com/r/FylFY1/2
应该可以,但是即使使用project 123
,我也可以通过验证.
It should work, but I can pass the validation even with project 123
.
UPDATE :它确实有效,我只是在错误的控制器上对其进行了测试,对不起...但是也许它仍然可以帮助其他人
UPDATE: It actually works, I just tested it in the wrong controller, im sorry... but maybe it will help others nevertheless
推荐答案
您的规则做得很好但是,您需要了解,用管道分隔的正则表达式指定验证规则可以引导进行不良行为.
Your rule is well done BUT you need to know, specify validation rules with regex separated by pipeline can lead to undesired behavior.
定义验证规则的正确方法应该是:
The proper way to define a validation rule should be:
$this->validate(request(), [
'projectName' =>
array(
'required',
'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
)
];
您可以阅读官方文档:
regex:pattern
regex:pattern
正在验证的字段必须与给定的正则表达式匹配.
The field under validation must match the given regular expression.
注意:使用正则表达式/not_regex模式时,可能需要在数组中指定规则,而不要使用管道定界符,尤其是在正则表达式包含管道字符的情况下.
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.
这篇关于Laravel 5.4-使用正则表达式进行验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!