Yii检查两个非数据库模型的输入是否相等


yii check input of two non database model if equals

我想比较模型中的两个输入

  class User extends CActiveRecord
  {
    public function tableName()
    {
        return '{{user}}';
    }
     public $newPassword;
     public $repeatPassword;

如何使用rules()做到这一点。注意$newPassword和$repeatPassword都不是数据库模型

this is my view

<div class="row">
    <?php echo $form->labelEx($model,'newPassword'); ?>
    <?php echo $form->textField($model,'newPassword',array('size'=>60,'maxlength'=>128)); ?>
    <?php echo $form->error($model,'newPassword'); ?>
</div>
<div class="row">
    <?php echo $form->labelEx($model,'repeatPassword'); ?>
    <?php echo $form->textField($model,'repeatPassword',array('size'=>60,'maxlength'=>128)); ?>
    <?php echo $form->error($model,'repeatPassword'); ?>
</div>

查看yii wiki的验证

public function rules() {
    return array(
        array('newPassword', 'required'),
        array('repeatPassword', 'required'),
        array('newPassword', 'compare', 'compareAttribute'=>'repeatPassword'),
    );
}

或者您可以编写自己的验证规则

public function rules() {
    return array(
        array('newPassword, repeatPassword', 'safe'),
        array('newPassword', 'checkPassword'),
    );
}
public function checkPassword($attribute,$params) {
    // return if there was no password input
    if (empty($this->newPassword) && empty($this->repeatPassword)) return;
    // if password does not match repeat password add validation error
    if ($this->newPassword != $this->repeatPassword)
        $this->addError('newPassword','Password does not match the Repeat Password.');
}