yii2 validation match regular expression pattern g

2020-05-06 13:13发布

问题:

following the rule of thumb never to trust data received from end users before putting it to good use, i tried one of the core validators' match. before placing it as pattern, ive tested the expression using online regex101 and regex debugger match sample string in 6 steps. However, when i put it in my rule and tried it, i got invalid input.

here's what i did:

public function rules()
    {
        return [
            [['name', 'code'], 'required'],
            [['name'], 'string', 'max' => 40],
            ['name','match','pattern'=>'/^([\w ]+)\z/i'],
            [['code'], 'string', 'max' => 9],
            ['code','match','pattern'=>'/^(?:[0-1])(?:[0-9])[0]+\z/'],
            [['name','code'], 'unique','attributes'=>['name','code']],
        ];

Here's the input:

region-regex-invalidInput

Please help needs assistance

回答1:

I guess what is really happening here is only client validation fails.

This is because PHP regex engine is different from the JS one. If you are using regex101 service to check the expression you can test it by switching the flavor on the left side menu from pcre (php) to javascript. If pcre is ok then it works on the server side, if javascript is ok it also works on the client side.

The solutions here are:

  • modify the pattern to work for JS,
  • switch client validation off,
  • prepare the rule to work only for server side (like using inline validator),
  • use AJAX validation.