Laravel 5.4 - 使用正则表达式验证
Laravel 5.4 - Validation with Regex
下面是我的项目名称规则:
$this->validate(request(), [
'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];
我正在尝试添加规则,使其必须以来自 a-z
或 A-z
的 字母开头,并且可以以数字结尾,但大多数情况下不能。
项目名称的有效值:
myproject123
myproject
MyProject
项目名称的值无效:
123myproject
!myproject
myproject 123
my project
my project123
我在线尝试了我的正则表达式:
https://regex101.com/r/FylFY1/2
它应该可以,但即使 project 123
我也可以通过验证。
更新:它确实有效,我只是在错误的控制器中测试了它,我很抱歉......但也许它会对其他人有所帮助
您的规则做得很好但是您需要知道,使用管道分隔的正则表达式指定验证规则可能会导致出现不良行为。
定义验证规则的正确方法应该是:
$this->validate(request(), [
'projectName' =>
array(
'required',
'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
)
];
您可以阅读 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.
下面是我的项目名称规则:
$this->validate(request(), [
'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];
我正在尝试添加规则,使其必须以来自 a-z
或 A-z
的 字母开头,并且可以以数字结尾,但大多数情况下不能。
项目名称的有效值:
myproject123
myproject
MyProject
项目名称的值无效:
123myproject
!myproject
myproject 123
my project
my project123
我在线尝试了我的正则表达式:
https://regex101.com/r/FylFY1/2
它应该可以,但即使 project 123
我也可以通过验证。
更新:它确实有效,我只是在错误的控制器中测试了它,我很抱歉......但也许它会对其他人有所帮助
您的规则做得很好但是您需要知道,使用管道分隔的正则表达式指定验证规则可能会导致出现不良行为。
定义验证规则的正确方法应该是:
$this->validate(request(), [
'projectName' =>
array(
'required',
'regex:/(^([a-zA-Z]+)(\d+)?$)/u'
)
];
您可以阅读 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.