Brett Brett - 22 days ago 10
PHP Question

Having issue with pattern match incorrectly validating in Yii 2

I have a bunch of validation rules within my

rules
method and all the errors seem to work, but having an issue with this one:

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


It validates, which is the incorrect behavior.

Am I doing something wrong here?

Answer

This pattern only checks first character. You need to correct it like below:

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

To make sure that Yii's matching is working, you can test it by writing @ (for example) as first character. Then, you can see that, validation works. So the problem is with your pattern.