php - Laravel 5.4 - 使用正则表达式进行验证

标签 php laravel laravel-5 laravel-5.4

以下是我的项目名称规则:

$this->validate(request(), [
    'projectName' => 'required|regex:/(^([a-zA-z]+)(\d+)?$)/u',
];

我正在尝试添加规则,使其必须以 a-zA-z 中的 字母开头,并且可以以数字结尾,但大多数不是。

项目名称的有效值:

myproject123
myproject
MyProject

项目名称的值无效:

123myproject
!myproject
myproject 123
my project
my project123

我在线尝试了我的正则表达式:

enter image description here

https://regex101.com/r/FylFY1/2

它应该可以工作,但即使使用 project 123 我也可以通过验证。

更新:它确实有效,我只是在错误的 Controller 中测试了它,我很抱歉......但也许它会帮助其他人

最佳答案

您的规则做得很好但是您需要知道,使用由管道分隔的正则表达式指定验证规则会导致出现不良行为。

定义验证规则的正确方法应该是:

$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.

关于php - Laravel 5.4 - 使用正则表达式进行验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42577045/

相关文章:

javascript - 将blade user.id路由传递给react js组件

php - CakePHP : Customized error message should display on the same page instead of moving some other page

excel - 导入excel时跳过重复行

php - 无法通过 Composer 在Windows上安装laravel 5

PHP-shoutbox 接受 php 标签或 html 标签作为文本而不是代码

Laravel 创建服务提供者参数 1 必须实现服务提供者

php - 使用 Eloquent 复杂查询 - Laravel 4

php - Laravel php artisan 配置 :cache and AWS S3 access error

javascript - HTTP post 将 null 附加到请求数据 ionic

php - 强制 json_encode 将(稀疏)数组编码为 php 中的索引数组