【问题标题】:YII Validation rules , regex not working in YIIYII 验证规则,正则表达式在 YII 中不起作用
【发布时间】:2014-12-15 09:10:25
【问题描述】:

我在 YII 中有以下验证规则,不知何故,正则表达式似乎不起作用:

Yii modal 中的规则:

public function rules()
    {
        return array(
            array('password, email, username, password_confirmation', 'required'),
            array('password','match', 'pattern'=> '/^[a-zA-Z]\w{5,20}$/','message'=>"{attribute} should contain only alphanumeric and underscore."),
            array('email_conf', 'numerical', 'integerOnly'=>true),
            array('username, email, login_source', 'length', 'max'=>150),
            array('email','email'),
            array('password, password_confirmation', 'length', 'min'=>6, 'max'=>200),
            array("password", "compare", "compareAttribute" => "password_confirmation"),
            array('fb_id', 'length', 'max'=>100),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, username, email, password, login_source, fb_id, email_conf', 'safe', 'on'=>'search'),
            array("password_confirmation, email_conf", "safe")
        );
    }

在上面的代码中,与我有关的行如下:

array('password','match', 'pattern'=> '/^[a-zA-Z]\w{5,20}$/','message'=>"{attribute} should contain only alphanumeric and underscore."),

正则表达式只接受字母作为第一个字符和特殊字符
不会被接受,空格也不会被接受。

现在不知何故,即使我使用了正确的 YII 语法 (check this on how to use regexes with YII)

正则表达式似乎不起作用。

我为这个模式创建了一个简单的 PHP 文本案例:

<?php

if (isset($_POST['submit'])) {

    $holder = $_POST['regex']; 
    $regrex = preg_match('/^[a-zA-Z]\w{5,20}$/', $holder);

    if ($regrex) {
        echo "Match";
    }
    else {
        echo "Not match";
    }
}


?>

<form action="" method="post" >

    <input type="text" name="regex"><br><br>
    <button type="submit" value="submit" name="submit">Submit</button>

</form>

并且正则表达式工作得很好!那么 YII 中的问题是什么,即使我正确地遵循了 YII 语法??

编辑:

视图文件中对应的标签如下:

<div class="">
       <?php echo $form->labelEx($model,'password'); ?>
      <?php echo $form->passwordField($model,'password',array('size'=>50,'maxlength'=>50)); ?>
      <?php echo $form->error($model,'password'); ?>
</div>

特纳利。

编辑: 控制器代码:

public function actionCreate()
       {
               $model=new User;

               // Uncomment the following line if AJAX validation is needed
               // $this->performAjaxValidation($model);

            if(isset($_POST['User']))
            {
            $username = $_POST['User'];
            if(isset($username['email'])) {
                $record=User::model()->find(array(
                  'select'=>'*',
                  'condition'=>'email=:email',
                  'params'=>array(':email'=>$username['email']))
              );
            }

            if($record===null){

                            $model->attributes=$_POST['User'];                       
                            $model->password = crypt($model->password,'salt');
                            $model->password_confirmation = crypt($model->password_confirmation,'salt');
                            //$model->password = $model->password;

                            if($model->save()){

                                // confirm mail send
                                $confirm_record=User::model()->find(array(
                          'select'=>'*',
                          'condition'=>'email=:email',
                          'params'=>array(':email'=>$username['email']))
                    );              

                    $to      = $username['email'];              
                    $subject = 'Confirm your Account';
                    $htmlBody = "Welcome and thank you for registering at Aaskar Pet Resort!<br>";
                    $htmlBody .= "Your account has now been created and you can log in by using your email address and password by visiting our website.<br>";
                    $htmlBody .= "<p><a style='text-decoration:none;' href ='".Yii::app()->request->hostInfo.''.$this->createUrl('site/confirmed',array('id'=> base64_encode($confirm_record['id'])))."'>Confirm your account</a></p>";
                    $htmlBody .= "<p>Upon logging in, you will be able to access other services including reservation for your pets, booking services and editing your account information.</p>";
                    $htmlBody .= "<p>Thanks,<br>Aaskar Pet Resort</p>";

                    $headers = "MIME-Version: 1.0" . "\r\n";
                    $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
                    $headers .= 'From: <donotreply@purplefront.net>' . "\r\n";

                    $sent = mail($to, $subject, $htmlBody, $headers);
                     if($sent){
                        $message = $this->dynamicStatus('create_success');
                        Yii::app()->user->setFlash('success', $message);
                                        $this->redirect(array('site/index'));
                                    }

                                //Yii::app()->user->setFlash('success', 'Account has been created');
                                    //$this->redirect(array('site/index'));
                            }

                          }else{
                            $message = $this->dynamicStatus('email_exist');
                            Yii::app()->user->setFlash('error', $message);
                          }
               }

               $this->render('create',array(
                       'model'=>$model,
               ));
       }

这里也是 pastebin 上面代码的链接,以防万一它有帮助:

Pastebin link

【问题讨论】:

  • 视图中是否有密码标签?因为如果没有,验证器将被{attribute} 卡住。您可以尝试将消息更改为"Password should contain only alphanumeric and underscore."
  • 您是否尝试修改您的消息?
  • @Dinistro 你在谈论 return array() right I.E. 中的第二行。 array('password','match', 'pattern'=> '/^[a-zA-Z]\w{5,20}$/','message'=>"{attribute} 应该只包含字母数字和下划线。"), ??
  • 尝试用array('password','match', 'pattern'=&gt; '/^[a-zA-Z]\w{5,20}$/','message'=&gt;"Password should contain only alphanumeric and underscore."),替换array('password','match', 'pattern'=&gt; '/^[a-zA-Z]\w{5,20}$/','message'=&gt;"{attribute} should contain only alphanumeric and underscore."),
  • @Dinistro 作为一个测试用例我尝试这样做:array('password','match', 'pattern'=> '/^password/' ,'message'=>"password should只包含字母数字和下划线。”),然后在密码字段中输入“密码”,测试失败,所以我仍然无法弄清楚我哪里出错了。

标签: php regex validation yii


【解决方案1】:

为什么只为search 场景保留password 参数safe()?

 array('id, username, email, password, login_source, fb_id, email_conf', 'safe', 'on'=>'search'),

您可能必须检查 from 使用的模型场景。为什么不尝试使这些在所有情况下都安全:

array('id, username, email, password, login_source, fb_id, email_conf', 'safe'),

更新

从您的控制器/操作代码中,我看到您在获取密码字段后立即执行密码加密。但是您错过了针对上述模型规则的验证。 因此,如果您想进行验证,请在加密之前进行:

 $model->attributes=$_POST['User']; 
 $model->validate();   // validation is performed                   
 $model->password = crypt($model->password,'salt');
 $model->password_confirmation = crypt($model->password_confirmation,'salt');
 ...
 // comment one or another of the following lines:
 $model->save(); // again validation is performed 
 $model->save(false); // no validation is performed when saving AR

如果您想在 save() 中使用已加密的密码逃避验证,请执行以下操作:$model-&gt;save(false);

【讨论】:

  • 你的意思是代替数组('id,用户名,电子邮件,密码,login_source,fb_id,email_conf','safe','on'=>'search'),我应该把它做成数组( 'id,用户名,电子邮件,密码,login_source,fb_id,email_conf','安全'),??那真的会做什么?
  • 不会将此规则限制为唯一的“搜索”场景。请参阅此处:yiiframework.com/wiki/266/understanding-scenarios/#hh1 这些属性将始终为 safe
  • 非常有见地!并感谢您的回答和时间,但我的问题是为什么我的模式正则表达式不能在 YII 中工作,因为它在普通 PHP 中工作得很好?
  • @Tenali_raman,可能还有一些其他问题使正则表达式应用程序对模型表单数据感到沮丧。您会在您的问题中提供更多信息(更新/创建控制器操作并查看表单本身)吗?
  • @lgor Savinkin 已编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多