在Yii 2中错误验证模式匹配的问题

Bre*_*ett 3 php regex yii yii2

我的方法中有一堆验证规则rules,所有错误似乎都有效,但是这个有问题:

['username', 'match', 'pattern' => '/[a-zA-Z0-9_-]+/', 'message' => 'Your username can only contain alphanumeric characters, underscores and dashes.'],
Run Code Online (Sandbox Code Playgroud)

它验证,这是不正确的行为.

我在这里做错了吗?

Ali*_*our 9

此模式仅检查第一个字符.你需要纠正它,如下所示:

['username', 'match', 'pattern' => '/^[a-zA-Z0-9_-]+$/', 'message' => 'Your username can only contain alphanumeric characters, underscores and dashes.'],
Run Code Online (Sandbox Code Playgroud)

为了确保Yii的匹配正常,您可以通过编写@(例如)作为第一个字符来测试它.然后,你可以看到,验证工作.所以问题出在你的模式上.