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.

Valid values for project name:

myproject123
myproject
MyProject

项目名称的值无效:

123myproject
!myproject
myproject 123
my project
my project123

我在网上试用了我的正则表达式:

enter image description here

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

它应该可以工作,但我可以通过验证,即使是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'
        )
];

You can read on the official docs:

regex:pattern

The field under validation must match the given regular expression.

注意:当使用regex/notregex模式时,它是may be necessary to specify rules in an array instead of using pipe delimiters,尤其是当正则表达式包含管道字符时.

Laravel相关问答推荐

子目录中具有Vue实例的Laravel不起作用

根据路径的开头重定向

在 Laravel 中设置多个 Vue 组件的问题

FileViewFinder.php 第 137 行中的 Laravel 5 InvalidArgumentException:未找到视图 [.admin]

Laravel 5 控制台( artisan )命令单元测试

如何通过一个 laravel 安装处理子域

验证规则 required_if 与其他条件(Laravel 5.4)

使用 Laravel 限制多态多对多关系中的相关记录

Laravel 4:读取由 javascript 设置的 cookie

在 Laravel 5 中扩展请求类

使用数据库用户提供程序时如何在 Laravel 中创建密码重置方法

php Laravel-遇到格式不正确的数值(在字符串上)

在 Laravel 容器中覆盖单例

如何访问 Carbon 对象类型?

如何将Carbon 转换为字符串,只取日期?

Laravel - 更新时禁用更新时间

如何在 Laravel 4 中使用 SHA1 加密而不是 BCrypt?

laravel 搜索多个以空格分隔的单词

判断行是否存在,Laravel

使用 Laravel Mix 合并多个文件