yii2 验证匹配正则表达式模式得到无效输入 [英] yii2 validation match regular expression pattern got invalid input

查看:23
本文介绍了yii2 验证匹配正则表达式模式得到无效输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遵循经验法则,在充分利用从最终用户那里收到的数据之前永远不要相信它,我尝试了其中一个核心验证器的匹配.在将其作为模式放置之前,我使用在线 regex101 和 regex 调试器匹配示例字符串分 6 个步骤测试了表达式.然而,当我把它放在我的规则中并尝试它时,我得到了无效的输入.

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.

这是我所做的:

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']],
        ];

这是输入:

region-regex-invalidInput

请帮助需要帮助

推荐答案

我想这里真正发生的只是客户端验证失败.

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

这是因为 PHP 正则表达式引擎与 JS 引擎不同.如果您使用 regex101 服务来检查表达式,您可以通过将左侧菜单上的风格从 pcre (php) 切换到 javascript 来测试它.如果 pcre 没问题,那么它可以在服务器端工作,如果 javascript 没问题,它也可以在客户端工作.

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.

这里的解决方案是:

  • 修改模式以适用于 JS,
  • 关闭客户端验证,
  • 准备规则仅适用于服务器端(例如使用内联验证器),
  • 使用 AJAX 验证.

这篇关于yii2 验证匹配正则表达式模式得到无效输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆