YII验证规则,正则表达式不在YII中工作

时间:2014-12-15 09:10:26

标签: php regex validation yii

我在YII中有以下规则进行验证,不管怎样,正则表达式似乎不起作用:

Yii模式中的规则:

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

1 个答案:

答案 0 :(得分:2)

为什么仅为password方案保留search参数safe()?

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

您可能必须检查使用的模型方案。为什么不尝试使这些场景安全:

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->save(false);