Laravel 5.4 - Validation with Regex(Laravel 5.4 - 使用正则表达式验证)
问题描述
以下是我的项目名称规则:
$this->validate(request(), [
'projectName' => 'required|regex:/(^([a-zA-z]+)(d+)?$)/u',
];
我正在尝试添加规则,使其必须以 来自 az
或 Az
的字母开头,并且可以以数字结尾,但大多数不是.强>
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: 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'
)
];
您可以阅读官方文档:
正则表达式:模式
验证字段必须与给定的正则表达式匹配.
The field under validation must match the given regular expression.
注意:当使用 regex/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 - 使用正则表达式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 5.4 - 使用正则表达式验证


基础教程推荐
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- PHP 守护进程/worker 环境 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01