Steve
Steve

Reputation: 1211

Comapring rule between two variables in rules not working in Yii

I am doing a function to change the users password. Inside of the Users model I have create three variable like the following.

public $oldPassword;
public $newPassword;
public $repatePassword;

Now I need to compare newPassword and repare password together and i added the followinf rule inside of the model.

public function rules()
{
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
    return array(
        array('username, password', 'required'),
        array('username', 'length', 'max'=>20),
        array('password', 'length', 'max'=>255),
        array('oldPassword', 'findPassword', 'on' => 'changePwd'),
        //array('repatePassword','compare','compareAttribute'=>'newPassword', 'on'=>'changePwd'),
        // The following rule is used by search().
        // @todo Please remove those attributes that should not be searched.
        array('id, username, password', 'safe', 'on'=>'search'),
    );
}

I have the following form.

<div class="row">
        <?php echo $form->labelEx($model,'Old Password'); ?>
        <?php echo $form->passwordField($model,'oldPassword',array('size'=>20,'maxlength'=>20)); ?>
        <?php echo $form->error($model,'oldPassword'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'New Password'); ?>
        <?php echo $form->passwordField($model,'newPassword',array('maxlength'=>255)); ?>
        <?php echo $form->error($model,'newPassword'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($model,'Repate Password'); ?>
        <?php echo $form->passwordField($model,'repatePassword',array('maxlength'=>255)); ?>
        <?php echo $form->error($model,'repatePassword'); ?>
    </div>

    <div class="row buttons">
        <?php echo CHtml::submitButton('Update'); ?>
    </div>

Now when I exactly put the exc same values in both of the fields it still gives me that the values are not the same. Why is this?

Upvotes: 1

Views: 116

Answers (1)

Willem Renzema
Willem Renzema

Reputation: 5187

Add the following rule to your rules() method.

array('oldPassword,newPassword,repatePassword','required','on'=>'changePwd')

Without a rule for an attribute, that attribute will NOT be massively assigned to the model and so will not be available for any validation.

Alternately, you can change required to be safe if you just want to allow assignment, and not make the attributes actually required, although in this case required makes sense to me.

Based on your rules, the reason it says they do not match is because newPassword is not being assigned, and so is an empty string being compared to your intended password.

Upvotes: 2

Related Questions