Search code examples
phpyiiyii-extensions

How to create client side self defined rule in yii


I want to use reset password functionality in Yii. For that I have 4 fields i.e email, currentPassword, newPassword, newPasswordRepeat.

I have used following rules in my model

array('email, currentPassword, newPassword, newPasswordRepeat', 'required'),
       array('newPasswordRepeat', 'compare', 'compareAttribute'=>'newPassword'),
        array('currentPassword', 'equalPasswords'),

where equalPasswords is my user defined rule which checks whether currentPassword password match with my original password or not.

public function equalPasswords($currentPassword)
{
    $oDbConnection = Yii::app()->db;
    $oCommand = $oDbConnection->createCommand('SELECT * FROM Superadmin_details where email=:email');
    $oCommand->bindParam(':email', Yii::app()->session['email'],PDO::PARAM_STR);
    $user=$oCDbDataReader = $oCommand->queryRow();

    if ($user['password'] != $currentPassword)

    $this->addError($currentPassword, 'Old password is incorrect.');
}

This rule gives error on server side, i.e when I click on Submit button, page gets reloaded and then error gets displayed.

I want to display error on client side like other errors.

And I have enabled client side validation in form.

<?php $form=$this->beginWidget('CActiveForm', array(
      'id'=>'contact-form',
      'enableClientValidation'=>true,

      'clientOptions'=>array(
          'validateOnSubmit'=>true,
      ),
)); ?>

Solution

  • Try to change

    $this->addError($currentPassword, 'Old password is incorrect.');
    

    to

    $this->addError('currentPassword', 'Old password is incorrect.');
    

    EDIT:

    Also, you need AJAX validation:

    <?php $form=$this->beginWidget('CActiveForm', array(
          'id'=>'contact-form',
          'enableClientValidation'=>true, 'enableAjaxValidation' => true,
          'clientOptions'=>array(
              'validateOnSubmit'=>true,
          ),
    )); ?>
    

    and in top of your controller action:

    if (array_key_exists('ajax', $_POST) && $_POST['ajax'] === 'contact-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
    }